import { create } from "zustand"

interface AuthState {
  token: string | null
  username: string | null
  role: string | null

  setAuth: (auth: { token: string; username: string; role: string }) => void
  clearAuth: () => void
  isLoggedIn: () => boolean
  isAdmin: () => boolean
}

function loadAuthFromStorage() {
  try {
    const token = localStorage.getItem("token")
    const username = localStorage.getItem("username")
    const role = localStorage.getItem("role")
    if (token && username && role) return { token, username, role }
  } catch {
    // localStorage may be unavailable
  }
  return { token: null, username: null, role: null }
}

export const useAuthStore = create<AuthState>((set, get) => {
  const stored = loadAuthFromStorage()
  return {
    token: stored.token,
    username: stored.username,
    role: stored.role,

    setAuth: ({ token, username, role }) => {
      localStorage.setItem("token", token)
      localStorage.setItem("username", username)
      localStorage.setItem("role", role)
      set({ token, username, role })
    },

    clearAuth: () => {
      localStorage.removeItem("token")
      localStorage.removeItem("username")
      localStorage.removeItem("role")
      set({ token: null, username: null, role: null })
    },

    isLoggedIn: () => !!get().token,
    isAdmin: () => {
      const r = get().role
      return r != null && (r.toUpperCase() === "ADMIN" || r.toUpperCase() === "ROLE_ADMIN")
    },
  }
})

export function getToken(): string | null {
  return useAuthStore.getState().token
}

export function isAdminRole(role: string | null): boolean {
  if (!role) return false
  const u = role.toUpperCase()
  return u === "ADMIN" || u === "ROLE_ADMIN"
}
