import { create } from "zustand";
import { adminApiRequest, apiRequest } from "../api/client";
import { isLoggedInAsAdmin, getAdminUser, setAdminUser, clearAdminTokens } from "../utils/adminAuth";

interface UserState {
  me: any | null;
  adminUser: any | null;
  loading: boolean;
  error: string | null;
  bootstrap: () => Promise<void>;
  bootstrapAdmin: () => Promise<void>;
  clear: () => void;
  clearAdmin: () => void;
}

export const useUserStore = create<UserState>((set) => ({
  me: null,
  adminUser: null,
  loading: false,
  error: null,

  bootstrap: async () => {
    set({ loading: true, error: null });
    try {
      const me = await apiRequest("/api/me");
      set({ me, loading: false });
    } catch (e: any) {
      set({ error: e?.message || "加载用户信息失败", loading: false });
    }
  },

  bootstrapAdmin: async () => {
    if (!isLoggedInAsAdmin()) {
      set({ adminUser: null });
      return;
    }
    const stored = getAdminUser();
    if (stored) {
      set({ adminUser: stored });
      return;
    }
    set({ loading: true, error: null });
    try {
      const adminUser = await adminApiRequest("/api/console/auth/me");
      setAdminUser(adminUser);
      set({ adminUser, loading: false });
    } catch (e: any) {
      clearAdminTokens();
      set({ adminUser: null, loading: false, error: e?.message || "管理员身份已失效" });
    }
  },

  clear: () => set({ me: null, loading: false, error: null }),

  clearAdmin: () => {
    clearAdminTokens();
    set({ adminUser: null });
  },
}));
