import { isAxiosError } from "axios";

type ValidationDetail = {
  loc?: (string | number)[];
  msg?: string;
};

function formatValidationDetail(detail: ValidationDetail[]): string {
  const passwordError = detail.find((item) => item.loc?.includes("password"));
  if (passwordError?.msg) {
    return passwordError.msg.replace(/^Value error, /, "");
  }
  const emailError = detail.find((item) => item.loc?.includes("email"));
  if (emailError?.msg) {
    return "Enter a valid email address";
  }
  return "Invalid email or password format";
}

export function formatAuthError(error: unknown, fallback: string): string {
  if (!isAxiosError(error)) {
    return fallback;
  }
  if (!error.response) {
    return "Cannot reach the API. Make sure the backend is running and reload the page.";
  }
  const detail = error.response?.data?.detail;
  if (typeof detail === "string") {
    return detail;
  }
  if (Array.isArray(detail) && detail.length > 0) {
    return formatValidationDetail(detail as ValidationDetail[]);
  }
  return fallback;
}
