import { isAxiosError } from "axios";
import { toast } from "sonner";

import i18n from "@/i18n";
import { getAdminSessionState } from "@/stores/admin-session";
import { readToken } from "@/stores/admin-token";
import { isApiEnvelope } from "@/types/api/envelope";
import { LotteryApiBizError } from "@/types/api/errors";

/** 与后端 {@see ErrorCode::AdminUnauthenticated} 一致 */
export const ADMIN_UNAUTHENTICATED_CODE = 8110;

/** 与后端 {@see ErrorCode::AdminAccountDisabled} 一致 */
export const ADMIN_ACCOUNT_DISABLED_CODE = 8113;

/** 登录验证码错误等，HTTP 可能为 401/422，不应踢出会话 */
const LOGIN_FORM_ERROR_CODES = new Set([8111, 8112]);

let authRejectHandling = false;

function isAdminLoginPath(): boolean {
  if (typeof window === "undefined") {
    return false;
  }

  return window.location.pathname === "/admin/login";
}

/** 未登录 / Token 失效 / 账号禁用（非普通权限 403） */
export function isAdminAuthRejected(err: unknown): boolean {
  if (err instanceof LotteryApiBizError) {
    return (
      err.code === ADMIN_UNAUTHENTICATED_CODE ||
      err.code === ADMIN_ACCOUNT_DISABLED_CODE
    );
  }

  if (!isAxiosError(err)) {
    return false;
  }

  const body = err.response?.data;
  const envelopeCode =
    body && typeof body === "object" && "code" in body
      ? (body as { code?: unknown }).code
      : undefined;

  if (
    typeof envelopeCode === "number" &&
    LOGIN_FORM_ERROR_CODES.has(envelopeCode)
  ) {
    return false;
  }

  if (
    envelopeCode === ADMIN_UNAUTHENTICATED_CODE ||
    envelopeCode === ADMIN_ACCOUNT_DISABLED_CODE
  ) {
    return true;
  }

  if (isApiEnvelope(body) && body.code !== 0) {
    return (
      body.code === ADMIN_UNAUTHENTICATED_CODE ||
      body.code === ADMIN_ACCOUNT_DISABLED_CODE
    );
  }

  const status = err.response?.status;
  if (status === 401) {
    return true;
  }

  if (status === 403 && envelopeCode === ADMIN_ACCOUNT_DISABLED_CODE) {
    return true;
  }

  return false;
}

export function redirectToAdminLogin(): void {
  if (typeof window === "undefined" || isAdminLoginPath()) {
    return;
  }

  const loginPath = "/admin/login";
  if (window.location.pathname !== loginPath) {
    window.location.replace(loginPath);
  }
}

/**
 * 清除本地会话并跳转登录页。可在 axios 拦截器、/auth/me 刷新等任意上下文调用。
 */
export function handleAdminAuthRejected(): void {
  if (typeof window === "undefined" || isAdminLoginPath()) {
    return;
  }
  if (authRejectHandling) {
    return;
  }

  authRejectHandling = true;

  const session = getAdminSessionState();
  const hadSession = session.bearerToken != null || readToken() != null;
  void fetch("/api/v1/admin/auth/logout", { method: "POST" }).catch(() => {
    // Best-effort HttpOnly cookie cleanup; the local session is cleared below.
  });
  session.clearSession();

  if (hadSession) {
    toast.error(
      i18n.t("auth.sessionExpired", {
        ns: "common",
        defaultValue: "Sign-in expired. Please log in again.",
      }),
    );
  }

  redirectToAdminLogin();

  queueMicrotask(() => {
    authRejectHandling = false;
  });
}
