import { createContext, useContext } from "react";
import type { Permission, Role, User } from "../api/types";

export interface AuthState {
  user: User | null;
  /** True while restoring a session from a stored token on first load. */
  initializing: boolean;
  login: (username: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  isAdmin: boolean;
  hasRole: (role: Role) => boolean;
  hasPermission: (perm: Permission) => boolean;
}

export const AuthContext = createContext<AuthState | null>(null);

export function useAuth(): AuthState {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error("useAuth must be used within <AuthProvider>");
  return ctx;
}
