"use client"

// Authoritative session context: fetches GET /auth/me once per mount and exposes
// the current role + permitted sidebar nav codes. Replaces trusting the stale,
// client-only `roleId` cached by lib/auth-session.ts for anything access-related
// (that cache remains display-only, e.g. for the header's user name).
import { createContext, useContext, useEffect, useState } from "react"

import { authApi } from "@/lib/api/auth"
import { MeResponse } from "@/types/rbac"

interface AuthContextValue {
  roleCode: string | null
  roleName: string | null
  navCodes: string[]
  /** True until the first `/auth/me` response lands. */
  loading: boolean
}

const AuthContext = createContext<AuthContextValue>({
  roleCode: null,
  roleName: null,
  navCodes: [],
  loading: true,
})

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [me, setMe] = useState<MeResponse | null>(null)

  useEffect(() => {
    let cancelled = false
    authApi
      .me()
      .then((res) => {
        if (!cancelled) setMe(res)
      })
      .catch(() => {
        // Unauthenticated/unreachable — fall back to "no permissions" rather than
        // crash the shell; proxy.ts already redirects unauthenticated users to /login.
        if (!cancelled) setMe({ roleCode: null, roleName: null, navCodes: [] })
      })
    return () => {
      cancelled = true
    }
  }, [])

  return (
    <AuthContext.Provider
      value={{
        roleCode: me?.roleCode ?? null,
        roleName: me?.roleName ?? null,
        navCodes: me?.navCodes ?? [],
        loading: me === null,
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth(): AuthContextValue {
  return useContext(AuthContext)
}
