import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { storage } from '@/lib/storage'
import type { AppMenu, UserInfo } from '@/types/system'

type AuthState = {
  token: string
  user: UserInfo | null
  menus: AppMenu[]
  setToken: (token: string) => void
  setUser: (user: UserInfo | null) => void
  setMenus: (menus: AppMenu[]) => void
  applySession: (payload: { token: string; user: UserInfo }) => void
  clearSession: () => void
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      token: storage.getToken(),
      user: null,
      menus: [],
      setToken: (token) => {
        storage.setToken(token)
        set({ token })
      },
      setUser: (user) => set({ user }),
      setMenus: (menus) => set({ menus }),
      applySession: ({ token, user }) => {
        storage.setToken(token)
        set({ token, user })
      },
      clearSession: () => {
        storage.clearToken()
        set({ token: '', user: null, menus: [] })
      },
    }),
    {
      name: 'gva-react-admin-auth',
      partialize: (state) => ({
        token: state.token,
        user: state.user,
      }),
    },
  ),
)
