/**
 * 管理端会话：HttpOnly Cookie 登录态 + 登录接口返回的 {@link AdminProfile}。
 *
 * - **组件内**：`useAdminProfile()`、`useAdminSessionStore(...)`
 * - **组件外**（axios、工具函数）：`getAdminProfile()`、`useAdminSessionStore.getState()`
 */
import { create } from "zustand";

import { fetchAdminMeDeduped } from "@/lib/admin-fetch-me";
import { setAdminBearerToken } from "@/lib/admin-auth";
import {
  handleAdminAuthRejected,
  isAdminAuthRejected,
} from "@/lib/admin-auth-reject";
import { readProfile, writeProfile } from "@/stores/admin-profile";
import { writeToken } from "@/stores/admin-token";
import type { AdminProfile } from "@/types/api/admin-auth";

export type AdminSessionState = {
  bearerToken: string | null;
  adminProfile: AdminProfile | null;
  /** Shell 路由守卫正在校验 `/auth/me` 时为 true，用于侧栏/顶栏骨架屏 */
  shellAuthPending: boolean;
  setShellAuthPending: (pending: boolean) => void;
  setBearerToken: (token: string | null) => void;
  setAdminProfile: (profile: AdminProfile | null) => void;
  clearSession: () => void;
  /** 从 HttpOnly Cookie 会话恢复管理员摘要（仅客户端） */
  rehydrate: () => void;
  refreshAdminProfile: () => Promise<void>;
  /** @deprecated 使用 {@link clearSession} */
  clearBearerToken: () => void;
};

export const useAdminSessionStore = create<AdminSessionState>((set, get) => ({
  bearerToken: null,
  adminProfile: null,
  shellAuthPending: false,

  setShellAuthPending: (pending) => {
    set({ shellAuthPending: pending });
  },

  setBearerToken: (token) => {
    const normalized = token?.trim() ? token.trim() : null;
    setAdminBearerToken(normalized);
    writeToken(normalized);
    if (!normalized) {
      writeProfile(null);
      set({ bearerToken: null, adminProfile: null });

      return;
    }
    set({ bearerToken: normalized });
  },

  setAdminProfile: (profile) => {
    writeProfile(profile);
    set({ adminProfile: profile });
  },

  clearSession: () => {
    setAdminBearerToken(null);
    writeToken(null);
    writeProfile(null);
    set({ bearerToken: null, adminProfile: null });
  },

  rehydrate: () => {
    if (typeof window === "undefined") {
      return;
    }
    const profile = readProfile();
    setAdminBearerToken(null);
    set({ bearerToken: "__cookie__", adminProfile: profile });
    void get().refreshAdminProfile();
  },

  refreshAdminProfile: async () => {
    try {
      const result = await fetchAdminMeDeduped();
      writeProfile(result.admin);
      set({ adminProfile: result.admin });
    } catch (err) {
      if (isAdminAuthRejected(err)) {
        handleAdminAuthRejected();
        return;
      }

      const cached = get().adminProfile ?? readProfile();
      if (cached) {
        set({ adminProfile: cached });
      }
    }
  },

  clearBearerToken: () => {
    get().clearSession();
  },
}));

/** React 组件：订阅当前管理员摘要（未登录或未缓存时为 `null`） */
export function useAdminProfile(): AdminProfile | null {
  return useAdminSessionStore((s) => s.adminProfile);
}

/** React 组件：是否已有 Token（已通过登录或 `rehydrate`） */
export function useAdminSignedIn(): boolean {
  return useAdminSessionStore((s) => s.bearerToken !== null);
}

/**
 * 任意运行上下文读取管理员摘要（不触发重渲染）。
 * 服务端为 `null`；客户端与页面水合后才有值。
 */
export function getAdminProfile(): AdminProfile | null {
  return useAdminSessionStore.getState().adminProfile;
}

/** 非 React 代码读取完整会话状态（含 `setBearerToken`、`clearSession` 等） */
export function getAdminSessionState(): AdminSessionState {
  return useAdminSessionStore.getState();
}
