export function resolveWorkspaceSlug(rawValue, defaultWorkspaceSlug) {
  return String(rawValue || defaultWorkspaceSlug || "").trim();
}

export function requireStringField(rawValue, fieldName) {
  const value = String(rawValue || "").trim();
  if (!value) {
    throw new Error(`${fieldName} is required`);
  }
  return value;
}

export function optionalString(rawValue) {
  if (rawValue === undefined) {
    return undefined;
  }
  return String(rawValue);
}

export function optionalTrimmedString(rawValue) {
  if (rawValue === undefined) {
    return undefined;
  }
  const value = String(rawValue).trim();
  if (!value) {
    return undefined;
  }
  return value;
}

export function optionalISODateTime(rawValue, fieldName) {
  if (rawValue === undefined) {
    return undefined;
  }
  const value = String(rawValue).trim();
  if (!value) {
    return undefined;
  }
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    throw new Error(`${fieldName} must be a valid ISO date-time string`);
  }
  return value;
}

export function ensureAtLeastOneField(body, message = "at least one field must be provided") {
  if (Object.keys(body).length === 0) {
    throw new Error(message);
  }
}

export function normalizeLimit(rawValue, defaultValue, maxValue) {
  if (rawValue === undefined || rawValue === null || rawValue === "") {
    return defaultValue;
  }
  const parsed = Number.parseInt(String(rawValue), 10);
  if (Number.isNaN(parsed) || parsed < 1 || parsed > maxValue) {
    throw new Error(`limit must be an integer between 1 and ${maxValue}`);
  }
  return parsed;
}
