import { reviewedChoices } from "@/features/shared/reviewChoices";
import { isApiSuccess } from "@/lib/api/errors";
import type {
  LoginResponseRecord,
  RegisterUserRecord,
  VerifyOtpRecord,
} from "@/features/auth/authRecords";
import apiClient from "@/lib/api/client";
import type { ApiResponse } from "@/lib/api/types";
import type { ChoiceItem } from "@/lib/choices";

/*
 * Request bodies, transcribed from each endpoint's own validation.
 *
 * Every shape below was read off the backend rather than inferred from the
 * forms that post it, so a key the API does not accept is a type error here
 * instead of a silently-ignored field. Sources are named per type. Laravel's
 * `validate()` ignores unknown keys rather than rejecting them (no
 * `RejectsUnknownWriteKeys` middleware is applied to any of these routes in
 * `routes/api.php`), so an extra key fails quietly — which is exactly why
 * these are worth spelling out.
 *
 * `nationality` is `"kuwaitis" | "other"` and `residency_status` is
 * `"resident" | "non_resident"` (`app/Enums/Nationality.php`,
 * `app/Enums/ResidencyStatus.php`); the UI's single combined choice is split
 * into the pair by `findNationalityResidency` in `data/Constants.ts`.
 */

/** `app/Enums/Nationality.php` — `personValues()` excludes `all`. */
export type NationalityValue = "kuwaitis" | "other";
/** `app/Enums/ResidencyStatus.php`. */
export type ResidencyStatusValue = "resident" | "non_resident";
/** `app/Enums/UserType.php` — `selfRegisterableValues()`. */
export type SelfRegisterableUserType = "volunteer" | "organization" | "voluntary_team";
/** The two OTP flows `verify_otp_or_token` / `resend_otp_or_token` accept. */
export type OtpType = "register" | "password";

/**
 * Narrow an `otp_type` that arrived from a URL or from session storage.
 *
 * Both OTP endpoints validate `type` with `Rule::in(['register','password'])`,
 * so anything else is a guaranteed 422. These values reach the app as free
 * strings — `?otp_type=` on `/email-verification`, and a nav-state payload —
 * and were previously forwarded unchecked. `register` is the default because
 * that is the flow the page is reached by when nothing says otherwise.
 */
export function asOtpType(value: unknown): OtpType {
  return value === "password" ? "password" : "register";
}

/**
 * Narrow a `user_type` that arrived from a URL or from session storage.
 *
 * `null` is preserved: `socialAuth` and `RegisterRequest` both mark the field
 * `nullable`, and omitting it makes the backend default to volunteer, so
 * forcing a value here would silently change what an organization signup
 * submits.
 */
export function asSelfRegisterableUserType(
  value: unknown
): SelfRegisterableUserType | null {
  return value === "organization" || value === "volunteer" || value === "voluntary_team"
    ? value
    : null;
}

/** `AuthController::login()` — four keys, two required. */
export interface LoginPayload {
  email: string;
  password: string;
  rememberMe?: boolean;
  is_opportunity?: boolean;
}

/**
 * `app/Http/Requests/Auth/RegisterRequest.php`.
 *
 * Only `email` is required; everything else is `nullable`, because one endpoint
 * serves the volunteer, organization and trainer signups. Posted as `FormData`
 * when it carries `profile_pic`, `documents` or `trainer_certificate`, and as a
 * plain object otherwise — hence the union on the request function.
 */
export interface RegisterPayload {
  occupation?: string;
  facebook_link?: string;
  instagram_link?: string;
  linkedin_link?: string;
  twitter_link?: string;
  whatsapp_link?: string;

  /** Client-review contract: registration must persist the single health-status answer. */
  health_concerns?: string;
  profile_pic?: File;
  interest_ids?: string[];
  email: string;
  password?: string;
  user_type?: SelfRegisterableUserType;
  first_name?: string;
  last_name?: string;
  phone_number?: string;
  country_code?: string;
  nickname?: string;
  /** Unique and fixed after sign-up; required for an organization or team. */
  username?: string;
  /** `master_choices.id` — an integer, per `exists:master_choices,id`. */
  gender?: number | string;
  organization_id?: number;
  organizer_type?: number | string;
  registration_number?: string;
  license_number?: string;
  latitude?: number | string;
  longitude?: number | string;
  nationality?: NationalityValue | "";
  residency_status?: ResidencyStatusValue | "";
  speaks_arabic?: boolean | string;
  birth_year?: number;
  dob?: string;
  preferred_language?: "en" | "ar";
  receive_reminder_emails?: boolean;
  do_not_disturb?: boolean;
  show_real_name?: boolean;
  wants_trainer?: boolean;
  trainer_types?: string[];
  bank_account_holder_name?: string;
  bank_name?: string;
  /** `size:30` — validated as an exact length, not a maximum. */
  iban?: string;
  iban_confirmation?: string;
  bank_account_ownership?: boolean;
  company_name?: string;
  civil_id?: string;
  passport_number?: string;
  volunteer_is_verified?: boolean;
  emergency_contact_name?: string;
  emergency_contact_phone?: string;
  emergency_contact_country_code?: string;
  emergency_contact_civil_id?: string;
  emergency_contact_relationship?: number | string;
}

/**
 * A `RegisterPayload` as multipart fields. Arrays go out as `key[]` entries:
 * `interest_ids` is validated `array`, and `String(["3","7"])` = `"3,7"` made
 * the trainer sign-up (the only multipart individual sign-up) a 422 whenever
 * an interest was ticked. Booleans are `1`/`0`; null/undefined are left out.
 */
export function appendRegisterPayload(formData: FormData, payload: RegisterPayload): void {
  Object.entries(payload).forEach(([key, value]) => {
    if (value === undefined || value === null) return;
    if (Array.isArray(value)) {
      value.forEach((item) => formData.append(`${key}[]`, String(item)));
      return;
    }
    if (typeof File !== "undefined" && value instanceof File) {
      formData.append(key, value);
      return;
    }
    formData.append(key, typeof value === "boolean" ? (value ? "1" : "0") : String(value));
  });
}

/** `AuthController::forgotPassword()` — one key. */
export interface ForgotPasswordPayload {
  email: string;
}

/**
 * `AuthController::changePassword()`.
 *
 * Serves both the reset-by-token flow and a signed-in change, which is why
 * `token` and `old_password` are each nullable: one or the other applies.
 * The password rules are `min:8` plus an uppercase and a digit.
 */
export interface ChangePasswordPayload {
  email: string;
  password: string;
  token?: string;
  old_password?: string;
}

/** `AuthController::verifyOtpOrToken()`. */
export interface VerifyOtpPayload {
  email: string;
  type: OtpType;
  otp: string;
}

/** `AuthController::resendOtpOrToken()`. */
export interface ResendOtpPayload {
  email: string;
  type: OtpType;
}

/**
 * `AuthController::socialAuth()` — a closed list of thirteen keys.
 *
 * The mandate form spreads a half-made user into this body, so the index
 * signature is deliberately absent: an unrecognised key would be dropped by
 * the backend without complaint, and naming the accepted set is the only way
 * that shows up.
 */
export interface SocialAuthPayload {
  occupation?: string;
  facebook_link?: string;
  instagram_link?: string;
  linkedin_link?: string;
  twitter_link?: string;
  whatsapp_link?: string;
  do_not_disturb?: boolean;
  receive_reminder_emails?: boolean;
  show_real_name?: boolean;
  /** Sent, but no longer identity (BE-160) — the backend reads the email out
      of the verified `social_token` and ignores this one. */
  email: string;
  social_media_provider: "google" | "linkedin";
  /**
   * BE-160 — **required**. Google: the GIS ID token (JWT `credential`), checked
   * against `GOOGLE_CLIENT_ID`; an OAuth access token is rejected. (LinkedIn
   * sign-in was cancelled by the client — answers p.6, item 19 — so the
   * website only ever sends "google".) 401 when it is invalid or expired, 503
   * when the provider cannot be reached.
   */
  social_token: string;
  /** Ignored for identity, like `email`. */
  social_media_id?: string;
  first_name?: string;
  last_name?: string;
  social_profile_pic_url?: string;
  /** `nullable` in the validation — null means "let the backend default". */
  user_type?: SelfRegisterableUserType | null;
  civil_id?: string;
  nationality?: NationalityValue | "";
  residency_status?: ResidencyStatusValue | "";
  passport_number?: string;
  nickname?: string;
  /** Unique and fixed after sign-up; required for an organization or team. */
  username?: string;
  company_name?: string;
  organizer_type?: number | string;
  /**
   * Sent, but **discarded** — `AuthController::socialAuth()` does not validate
   * it (only `updateAccount()` and `RegisterRequest` do), and `AuthController`
   * is not one of the controllers using `RejectsUnknownWriteKeys`, so the key
   * is silently ignored rather than rejected. One of the seven fields in
   * BE-105. Kept on the type because the screens do send it and it documents
   * the intent; it will start taking effect when BE-105 is fixed.
   */
  preferred_language?: string;
}

export const loginRequest = async (
  credentials: LoginPayload
): Promise<ApiResponse<LoginResponseRecord>> => {
  const { data } = await apiClient.post("/login/", credentials);
  return data;
};

/* No token in the response: registering does not sign the account in — the
   flow continues through OTP verification and then login. */
export const registerRequest = async (
  credentials: RegisterPayload | FormData
): Promise<ApiResponse<RegisterUserRecord>> => {
  const { data } = await apiClient.post("/register/", credentials);
  if (!isApiSuccess(data)) throw data;
  return data;
};

/* `data: null` — the outcome is the `msg`, which `ForgotPasswordForm` shows. */
export const forgotPasswordRequest = async (
  credentials: ForgotPasswordPayload
): Promise<ApiResponse<null>> => {
  const { data } = await apiClient.post("/forgot-password/", credentials);
  if (!isApiSuccess(data)) throw data;
  return data;
};

/**
 * Both `type` values answer with `{ token, user_id }` — but the two tokens are
 * different kinds of thing under one key. See `VerifyOtpRecord`.
 */
export const emailVerificationRequest = async (
  credentials: VerifyOtpPayload
): Promise<ApiResponse<VerifyOtpRecord>> => {
  const { data } = await apiClient.post("/verify_otp_or_token/", credentials);
  if (!isApiSuccess(data)) throw data;
  return data;
};

export const resendOtpRequest = async (
  credentials: ResendOtpPayload
): Promise<ApiResponse<null>> => {
  const { data } = await apiClient.post("/resend_otp_or_token/", credentials);
  if (!isApiSuccess(data)) throw data;
  return data;
};

export const changePasswordRequest = async (
  credentials: ChangePasswordPayload
): Promise<ApiResponse<null>> => {
  const { data } = await apiClient.post("/change-password/", credentials);
  if (!isApiSuccess(data)) throw data;
  return data;
};

export const passSocialInfoRequest = async (
  /* `FormData` as well as a plain body: `useCompleteDetails` posts an
     organization's licence documents through this same endpoint. */
  credentials: SocialAuthPayload | FormData
): Promise<ApiResponse<LoginResponseRecord>> => {
  const { data } = await apiClient.post("/social-auth/", credentials);
  if (!isApiSuccess(data)) throw data;
  return data;
};

/**
 * Does this email or nickname already exist?
 *
 * The response carries only the keys that were asked about — verified against
 * `AuthController::checkUser()`, which builds `$result` one branch at a time —
 * so both are optional, and sending neither is a 400 rather than an empty
 * answer.
 */
export interface CheckUserQuery {
  email?: string;
  nickname?: string;
  /** Unique and fixed after sign-up; required for an organization or team. */
  username?: string;
}

export interface CheckUserResult {
  email?: {
    is_new_user: boolean;
    is_active: boolean;
    needs_activation: boolean;
  };
  nickname?: { is_new_user: boolean };
  /** `users.username`, the field sign-up enforces as unique (backend `1983649`+). */
  username?: { is_new_user: boolean };
}

/**
 * Availability query for the sign-up username. Sign-up submits the value as
 * `username`, so that is the branch asked about; `nickname` is sent too so an
 * API that predates the `username` branch still answers.
 */
export function usernameAvailabilityQuery(value: string): CheckUserQuery {
  const trimmed = value.trim();
  return { username: trimmed, nickname: trimmed };
}

/** `null` = not answered; the UI treats that as "not shown as available". */
export function readUsernameAvailability(result: CheckUserResult | undefined): boolean | null {
  return result?.username?.is_new_user ?? result?.nickname?.is_new_user ?? null;
}

export const checkUserRequest = async (
  credentials: CheckUserQuery
): Promise<ApiResponse<CheckUserResult>> => {
  const { data } = await apiClient.post("/check-user/", credentials);
  return data;
};

export const getDropdownChoicesRequest = async (
  type: string
): Promise<ApiResponse<ChoiceItem[]>> => {
  const { data } = await apiClient.get<ApiResponse<ChoiceItem[]>>(`/choices/${type}/`);
  return { ...data, data: Array.isArray(data.data) ? reviewedChoices(type, data.data) : data.data };
};
