import { getAuthApiOrigin } from "./env";

export type AuthMode = "sign-in" | "sign-up" | "forgot-password";
export type AuthFormErrors = Partial<
  Record<"name" | "email" | "password", string>
>;

export type AuthEnvironment = "proxy" | "local-4000" | "local-3000";

export const AUTH_ENVIRONMENT_TARGETS: Record<AuthEnvironment, string> = {
  proxy: "same-origin (Next rewrite)",
  "local-3000": "http://localhost:3000",
  "local-4000": "http://localhost:4000",
};

export function getAuthTargetForEnvironment(environment: AuthEnvironment): string {
  if (environment === "proxy") return getAuthApiOrigin();
  return AUTH_ENVIRONMENT_TARGETS[environment];
}

export function extractAuthErrorMessage(error: unknown): string {
  if (error && typeof error === "object") {
    const e = error as Record<string, unknown>;
    if (typeof e.message === "string") return e.message;
    if (
      e.error &&
      typeof e.error === "object" &&
      typeof (e.error as Record<string, unknown>).message === "string"
    ) {
      return (e.error as Record<string, string>).message;
    }
    if (typeof e.statusText === "string") return e.statusText;
  }
  if (typeof error === "string") return error;
  return "Request failed";
}

export function validateAuthForm(
  mode: AuthMode,
  email: string,
  password: string,
  name: string,
): AuthFormErrors {
  const errors: AuthFormErrors = {};
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  if (!email.trim()) errors.email = "Email is required";
  else if (!emailRegex.test(email)) {
    errors.email = "Enter a valid email address";
  }

  if (mode !== "forgot-password") {
    if (!password) errors.password = "Password is required";
    else if (password.length < 8) {
      errors.password = "Password must be at least 8 characters";
    }
  }

  if (mode === "sign-up" && !name.trim()) {
    errors.name = "Name is required";
  }

  return errors;
}
