/**
 * Normalize email to match backend storage (lowercase + trim).
 * Use on every form submit that includes an email field, so what
 * the user sees and what the backend stores stays in sync.
 */
export const normalizeEmail = (email: string | null | undefined): string => {
  return email?.toLowerCase().trim() ?? "";
};

type ApiErrorLike = {
  response?: {
    status?: number;
    data?: { message?: string | string[] };
  };
};

const getErrorMessage = (error: unknown): string => {
  const e = error as ApiErrorLike;
  const msg = e?.response?.data?.message;
  if (Array.isArray(msg)) return msg[0] ?? "";
  return msg ?? "";
};

const is400 = (error: unknown): boolean => {
  return (error as ApiErrorLike)?.response?.status === 400;
};

/**
 * Detect "email already exists" error from backend.
 * Backend returns: HTTP 400 { message: "A user with this email already exists" }
 */
export const isEmailAlreadyExistsError = (error: unknown): boolean => {
  return is400(error) && getErrorMessage(error).toLowerCase().includes("email already exists");
};

/**
 * Detect "phone number already exists" error from backend.
 */
export const isPhoneAlreadyExistsError = (error: unknown): boolean => {
  return is400(error) && getErrorMessage(error).toLowerCase().includes("phone number already exists");
};
