import { create } from 'zustand'
import { persist } from 'zustand/middleware'

interface User {
  id: string
  email: string
  full_name: string
  role: 'admin' | 'global_admin' | 'tenant_admin' | 'project_manager' | 'client'
  is_active: boolean
}

/** True for any role that has full administrative access. */
export const isAdmin = (user: User | null): boolean =>
  user?.role === 'admin' || user?.role === 'global_admin' || user?.role === 'tenant_admin'

/** True for admin or project_manager (privileged users). */
export const isPrivileged = (user: User | null): boolean =>
  isAdmin(user) || user?.role === 'project_manager'

interface AuthState {
  token: string | null
  user: User | null
  setAuth: (token: string, user: User) => void
  logout: () => void
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      token: null,
      user: null,
      setAuth: (token, user) => set({ token, user }),
      logout: () => set({ token: null, user: null }),
    }),
    { name: 'schaeffler-auth' },
  ),
)
