/**
 * 认证状态管理
 * - token 持久化到 localStorage
 * - 登录/登出
 * - 用户信息（含权限码列表）
 */

import { create } from 'zustand';
import { api } from '@/api/request';

/** 用户信息 */
interface User {
  id: number;
  phone: string;
  name: string;
  /** 角色等级：0普通 1企业管理员 2总管理员 */
  role: number;
  /** 用户拥有的权限码列表 */
  permissions: string[];
}

/** 登录参数 */
interface LoginParams {
  phone: string;
  password: string;
}

/** 登录响应 */
interface LoginResponse {
  token: string;
  user: User;
}

/** 认证状态 */
interface AuthState {
  token: string | null;
  user: User | null;
  loading: boolean;
  isAuthenticated: boolean;
  login: (params: LoginParams) => Promise<void>;
  logout: () => void;
  /** 从 localStorage 恢复 token 并从服务端获取用户信息 */
  restore: () => Promise<void>;
  /** 获取当前用户权限码集合 */
  getPermissions: () => string[];
}

export const useAuthStore = create<AuthState>((set, get) => ({
  token: localStorage.getItem('token'),
  user: null,
  loading: !!localStorage.getItem('token'),
  isAuthenticated: false,

  login: async (params: LoginParams) => {
    set({ loading: true });
    try {
      const res = await api.post<LoginResponse>('/auth/login', params);
      const { token, user } = res.data;
      localStorage.setItem('token', token);
      set({ token, user, isAuthenticated: true, loading: false });
    } catch {
      set({ loading: false });
      throw new Error('登录失败');
    }
  },

  logout: () => {
    localStorage.removeItem('token');
    set({ token: null, user: null, isAuthenticated: false });
  },

  restore: async () => {
    const token = localStorage.getItem('token');
    if (!token) return;

    set({ loading: true });
    try {
      const res = await api.get<{ id: number; name: string; phone: string; role: number; permissions: string[] }>('/auth/me');
      const { id, name, phone, role, permissions } = res.data;
      set({
        token,
        user: { id, name, phone, role, permissions },
        isAuthenticated: true,
        loading: false,
      });
    } catch {
      // token 无效或过期，清除本地存储
      localStorage.removeItem('token');
      set({ token: null, user: null, isAuthenticated: false, loading: false });
    }
  },

  getPermissions: () => {
    const { user } = get();
    return user?.permissions ?? [];
  },
}));
