/**
 * KRA - User Model (Zustand Store)
 * User authentication and info management
 */
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { clearAuth, setToken as saveToken, setOsType } from '@/utils/auth';

export interface UserAuthority {
  authorityId: string | number;
  authorityName: string;
  defaultRouter?: string;
}

export interface UserInfo {
  uuid: string;
  userName: string;
  nickName: string;
  headerImg: string;
  authority: UserAuthority;
  authorities?: UserAuthority[];
  sideMode?: string;
  activeColor?: string;
  baseColor?: string;
  originSetting?: Record<string, any>;
}

interface UserState {
  userInfo: UserInfo;
  token: string;
  loading: boolean;
}

interface UserActions {
  setUserInfo: (info: Partial<UserInfo>) => void;
  setToken: (token: string) => void;
  setLoading: (loading: boolean) => void;
  resetUserInfo: (value?: Partial<UserInfo>) => void;
  clearUser: () => void;
}

const initialUserInfo: UserInfo = {
  uuid: '',
  userName: '',
  nickName: '',
  headerImg: '',
  authority: {
    authorityId: '',
    authorityName: '',
    defaultRouter: '',
  },
  authorities: [],
};

export const useUserStore = create<UserState & UserActions>()(
  persist(
    (set, get) => ({
      userInfo: initialUserInfo,
      token: '',
      loading: false,

      setUserInfo: (info) => {
        set((state) => ({
          userInfo: { ...state.userInfo, ...info },
        }));
      },

      setToken: (token) => {
        saveToken(token);
        set({ token });
      },

      setLoading: (loading) => {
        set({ loading });
      },

      resetUserInfo: (value = {}) => {
        set((state) => ({
          userInfo: { ...state.userInfo, ...value },
        }));
      },

      clearUser: () => {
        clearAuth();
        set({
          userInfo: initialUserInfo,
          token: '',
        });
      },
    }),
    {
      name: 'kra-user-storage',
      partialize: (state) => ({
        token: state.token,
        userInfo: state.userInfo,
      }),
    }
  )
);

// Helper hooks
export const useToken = () => useUserStore((state) => state.token);
export const useUserInfo = () => useUserStore((state) => state.userInfo);
export const useIsLoggedIn = () => useUserStore((state) => !!state.token);

export default useUserStore;
