// UI-side permission helpers. The rules themselves live server-side
// (apps/api/src/auth/abilities.ts) and arrive resolved on `user.abilities` via
// /auth/me — this module just reads that map. Gating here is cosmetic (show or
// hide a control); the API enforces every write regardless.

import { createContext, useContext } from "react";
import type { Ability, AuthUser } from "./types";

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

/** The signed-in user (or null while loading). */
export function useAuth(): AuthUser | null {
  return useContext(AuthContext);
}

/** Whether the current user may perform `ability`. False when not loaded. */
export function useCan(ability: Ability): boolean {
  const user = useAuth();
  return user?.abilities?.[ability] ?? false;
}

export function can(user: AuthUser | null, ability: Ability): boolean {
  return user?.abilities?.[ability] ?? false;
}
