import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { IUserInfo, ITenant } from '@/interfaces/database/user-setting';
import type { ITenantInfo } from '@/interfaces/database/knowledge';

interface UserState {
  // 用户信息
  userInfo: IUserInfo | null;
  // 租户信息
  tenantInfo: ITenantInfo | null;
  // 租户列表
  tenantList: ITenant[];
  // 加载状态
  isLoading: boolean;
  // 错误信息
  error: string | null;
  
  // Actions
  setUserInfo: (userInfo: IUserInfo | null) => void;
  setTenantInfo: (tenantInfo: ITenantInfo | null) => void;
  setTenantList: (tenantList: ITenant[]) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  clearUserData: () => void;
  
  // 初始化用户数据
  initializeUserData: () => Promise<void>;
}

export const useUserStore = create<UserState>()(
  persist(
    (set, get) => ({
      // 初始状态
      userInfo: null,
      tenantInfo: null,
      tenantList: [],
      isLoading: false,
      error: null,

      // Actions
      setUserInfo: (userInfo) => set({ userInfo }),
      setTenantInfo: (tenantInfo) => set({ tenantInfo }),
      setTenantList: (tenantList) => set({ tenantList }),
      setLoading: (isLoading) => set({ isLoading }),
      setError: (error) => set({ error }),
      
      clearUserData: () => set({
        userInfo: null,
        tenantInfo: null,
        tenantList: [],
        error: null,
      }),

      // 初始化用户数据方法
      initializeUserData: async () => {
        // 初始化时会在 UserDataProvider 中调用
      },
    }),
    {
      name: 'user-store', // 持久化存储的key
      partialize: (state) => ({
        // 只持久化这些字段
        userInfo: state.userInfo,
        tenantInfo: state.tenantInfo,
        tenantList: state.tenantList,
      }),
    }
  )
);