import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { queryClient } from '../main'

interface User {
  id: string
  orgId: string | null
  name: string
  phone: string
  role: 'SUPER_ADMIN' | 'ADMIN' | 'HR' | 'VIEWER'
}

interface AuthState {
  user: User | null
  accessToken: string | null
  refreshToken: string | null
  isAuthenticated: boolean
  setAuth: (user: User, accessToken: string, refreshToken: string) => void
  updateToken: (accessToken: string) => void
  logout: () => void
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      accessToken: null,
      refreshToken: null,
      isAuthenticated: false,
      setAuth: (user, accessToken, refreshToken) => {
        queryClient.clear()
        set({ user, accessToken, refreshToken, isAuthenticated: true })
      },
      updateToken: (accessToken) => set({ accessToken }),
      logout: () => {
        queryClient.clear()
        set({ user: null, accessToken: null, refreshToken: null, isAuthenticated: false })
      },
    }),
    { name: 'auth-storage' },
  ),
)
