"use client";

import { createContext, useContext, type ReactNode } from "react";

import type { AppPermissions } from "@/src/lib/permissions";
import type { UserRole } from "@/src/types/user";

interface PermissionsContextValue {
  ruolo: UserRole;
  permissions: AppPermissions;
}

const PermissionsContext = createContext<PermissionsContextValue | null>(null);

export function PermissionsProvider({
  ruolo,
  permissions,
  children,
}: {
  ruolo: UserRole;
  permissions: AppPermissions;
  children: ReactNode;
}) {
  return (
    <PermissionsContext.Provider value={{ ruolo, permissions }}>
      {children}
    </PermissionsContext.Provider>
  );
}

export function usePermissions(): PermissionsContextValue {
  const ctx = useContext(PermissionsContext);
  if (!ctx) {
    throw new Error("usePermissions deve essere usato dentro PermissionsProvider");
  }
  return ctx;
}
