/**
 * authStore — 用户/workspace/role/token
 * 扒 banana 范式，全新重建
 */
import { create } from 'zustand';
import { User, UserRole, AuthMeResponse } from '@/types/index';
import { api } from '@/lib/api';

interface AuthState {
  user: User | null;
  role: UserRole | null;
  workspaceId: number | null;
  isAuthenticated: boolean;
  isLoading: boolean;

  login: (token: string, user: User) => void;
  logout: () => void;
  setWorkspace: (workspaceId: number, role: UserRole, token: string) => void;
  fetchMe: () => Promise<void>;
  endLoading: () => void;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: null,
  role: null,
  workspaceId: null,
  isAuthenticated: false,
  // 初始为 true：首屏未知是否已登录，先标加载中，等 AuthGuard 校验 token 后再落定。
  // 否则直接访问受保护页时守卫会在 fetchMe 前误判未登录→踢回 /login（竞态）。
  isLoading: true,

  login(token, user) {
    api.setToken(token);
    set({
      user,
      role: user.role,
      workspaceId: user.current_workspace_id,
      isAuthenticated: true,
      isLoading: false,
    });
  },

  logout() {
    api.clearToken();
    set({ user: null, role: null, workspaceId: null, isAuthenticated: false, isLoading: false });
  },

  endLoading() {
    set({ isLoading: false });
  },

  setWorkspace(workspaceId, role, token) {
    api.setToken(token);
    set((s) => ({
      workspaceId,
      role,
      user: s.user ? { ...s.user, current_workspace_id: workspaceId, role } : null,
    }));
  },

  async fetchMe() {
    set({ isLoading: true });
    try {
      const data = await api.get<AuthMeResponse>('/api/v1/auth/me');
      set({
        user: data,
        role: data.role,
        workspaceId: data.current_workspace_id,
        isAuthenticated: true,
        isLoading: false,
      });
    } catch {
      set({ isLoading: false });
    }
  },
}));
