/**
 * The API reports failures as
 *
 *   { key: "fail", msg: "Validation error", code: 422,
 *     response_status: { error: true, validation_errors: { civil_id: ["..."] } } }
 *
 * The messages are already localized by the backend from the `x-lang` / `Lang`
 * request header, so there is nothing to pick per language here.
 *
 * An older revision returned `{ errors: { civil_id: { en, ar } } }` instead, and
 * a fair amount of the app still reads that shape. Both are handled so a screen
 * can be migrated without waiting on every endpoint.
 */

import { localizeApiErrorText } from "./errorLocalization";

/** The legacy `{ en, ar }` message pair. */
export type LegacyFieldError = Record<string, string>;

/**
 * A 2xx status is not enough: the API answers a rejected request with HTTP 200
 * and `key: "fail"` often enough that every caller acting on `data` has to look
 * at the envelope rather than at the status code.
 */
export function isApiSuccess(response: unknown): boolean {
  if (!response || typeof response !== "object") return false;
  const envelope = response as {
    key?: string;
    response_status?: { error?: boolean };
  };
  return envelope.key === "success" && !envelope.response_status?.error;
}

/**
 * A failed response's body, as the API actually shapes it.
 *
 * Exported because some call sites need a field the message helpers below do
 * not cover — `useLoginForm` branches on `action === "verify_otp"`,
 * `ForgotPasswordForm` looks for "is not active" inside
 * `errors.non_field_errors`, `VerifyReport` renders `message`. Those were each
 * doing it behind `catch (error: any)`, which made the whole body untyped.
 * Reach for `getApiErrorBody` instead; prefer the message helpers when they
 * suffice.
 */
export interface ErrorPayload {
  msg?: string;
  /** Some endpoints send `message` rather than `msg`. */
  message?: string;
  /**
   * The envelope's `data`, which `ApiResponse` populates on failures too.
   *
   * Verified against `AuthController` line 712: an unverified account rejected
   * at login returns 403 with
   * `data: { action: "verify_otp", otp_type, email, is_active }`, alongside the
   * field error under `response_status.validation_errors.email`. `action` is
   * the authoritative next-step signal and is preferred over matching on
   * message text — see `useLoginForm`, where the text pattern has already gone
   * stale once.
   */
  data?: {
    action?: string;
    otp_type?: string;
    email?: string;
    is_active?: boolean;
    /** `"user_banned"` on a banned account's sign-in (403) or request (401). */
    error_code?: string;
    ban_type?: "manual" | "auto";
    ban_reason?: string | null;
    ban_duration_days?: number | null;
    ban_ends_at?: string | null;
  };
  /**
   * Some endpoints answer with a pre-localized pair rather than the
   * header-localized `msg`. Fifteen call sites were reaching for
   * `` error.response.data[`message_${language}`] `` by hand, each behind its
   * own `catch (error: any)`; `getLocalizedApiMessage` below does it once.
   */
  message_en?: string;
  message_ar?: string;
  response_status?: {
    validation_errors?: Record<string, string[] | string> | unknown[];
  };
  errors?: Record<string, LegacyFieldError | string[] | string>;
}

/** The key `ApiRefusal` puts its stable code under, in `data` and in the error bag. */
const REASON_CODE_KEY = "reason_code";

/** The stable refusal code (`data.reason_code`, BE-188), or null. */
export function getApiReasonCode(error: unknown): string | null {
  const code = (getPayload(error)?.data as { reason_code?: unknown } | undefined)?.reason_code;
  return typeof code === "string" && code ? code : null;
}

/**
 * A registration refused because the account is banned: 403 with
 * `data.error_code: "user_banned"`. Since backend `a47169a` an automatic
 * absence ban keeps the session (approved decision 6) and meets the person
 * here, at registration (PDF p.43). The response interceptor has already
 * opened the ban popup with the reason, length, end date and admin email, so
 * a caller only closes its own form rather than toasting the same text again.
 */
export function isBanRefusal(error: unknown): boolean {
  return getPayload(error)?.data?.error_code === "user_banned";
}

/**
 * The failed response's body, or `null` when the throw carried none.
 *
 * Handles all three shapes a caller sees: a thrown axios error (body on
 * `response.data`), a `fetch().json()` body, and an already-unwrapped payload.
 */
export function getApiErrorBody(error: unknown): ErrorPayload | null {
  return getPayload(error);
}

/** Unwrap an axios error, a `fetch().json()` body, or an already-unwrapped payload. */
function getPayload(error: unknown): ErrorPayload | null {
  if (!error || typeof error !== "object") return null;
  const maybeAxios = error as { response?: { data?: unknown } };
  const body = maybeAxios.response?.data ?? error;
  return body && typeof body === "object" ? (body as ErrorPayload) : null;
}

function firstString(value: unknown, language: string): string | null {
  if (typeof value === "string") return value;
  if (Array.isArray(value)) {
    const found = value.find((entry) => typeof entry === "string");
    return typeof found === "string" ? found : null;
  }
  if (value && typeof value === "object") {
    // Legacy `{ en, ar }` shape.
    const localized = value as LegacyFieldError;
    return localized[language.toLowerCase().startsWith("ar") ? "ar" : "en"] || localized.en || localized.ar || null;
  }
  return null;
}

/**
 * Field name → message, for the fields the API rejected. Empty when the failure
 * carried no per-field detail (network error, 500, plain `msg`-only response).
 */
export function getApiFieldErrors(
  error: unknown,
  language = "en"
): Record<string, string> {
  const payload = getPayload(error);
  if (!payload) return {};

  const raw = payload.response_status?.validation_errors ?? payload.errors;
  // A success-shaped envelope carries `validation_errors: []`.
  if (!raw || Array.isArray(raw) || typeof raw !== "object") return {};

  const fields: Record<string, string> = {};
  for (const [field, value] of Object.entries(raw)) {
    // `ApiRefusal` (BE-188) copies its machine code into the error bag as
    // `reason_code: ["account_deactivated"]`. It is not a field and not a
    // message: showing it put the raw code on screen instead of the
    // localized `msg` (sign-in, registration, deletion refusals…).
    if (field === REASON_CODE_KEY) continue;
    const message = firstString(value, language);
    if (message) fields[field] = localizeApiErrorText(message, language, language.startsWith("ar") ? payload.message_ar || payload.msg : payload.message_en || payload.msg);
  }
  return fields;
}

/** Every message the API returned, in field order, falling back to `msg`. */
export function getApiErrorMessages(
  error: unknown,
  language = "en"
): string[] {
  const messages = Object.values(getApiFieldErrors(error, language));
  if (messages.length > 0) return [...new Set(messages)];

  const payload = getPayload(error);
  const msg = (language.startsWith("ar") ? payload?.message_ar : payload?.message_en) || payload?.msg;
  return typeof msg === "string" && msg ? [localizeApiErrorText(msg, language)] : [];
}

/**
 * The `message_en` / `message_ar` message, if the endpoint sent one.
 *
 * Separate from `getApiErrorMessage` because these endpoints put the text at
 * the top level of the body under a language-suffixed key rather than in `msg`
 * or in `validation_errors`. Falls through to the generic message handling, so
 * one call covers both conventions.
 */
export function getLocalizedApiMessage(
  error: unknown,
  language = "en",
  fallback = ""
): string {
  const payload = getPayload(error);
  const localized =
    language === "ar" ? payload?.message_ar : payload?.message_en;
  if (typeof localized === "string" && localized) return localizeApiErrorText(localized, language);
  return getApiErrorMessage(error, language, fallback);
}

/** The single message worth showing, or `fallback` when the API said nothing useful. */
export function getApiErrorMessage(
  error: unknown,
  language = "en",
  fallback = ""
): string {
  return getApiErrorMessages(error, language)[0] || fallback;
}

/** The read was answered 404: the record does not exist (or is not visible to this viewer). */
export function isNotFoundError(error: unknown): boolean {
  return (error as { response?: { status?: number } } | null)?.response?.status === 404;
}

/**
 * What a failed detail read says (p.37: error ≠ empty). The server's message
 * first; otherwise «not found» only for a 404 — a network error or a 500 must
 * not claim the record does not exist, it says the load failed (with a retry).
 */
export function getReadErrorMessage(
  error: unknown,
  language: string,
  fallbacks: { notFound: string; failed: string }
): string {
  return getLocalizedApiMessage(error, language) || (isNotFoundError(error) ? fallbacks.notFound : fallbacks.failed);
}
