import { Permission } from "@/shared/dto/user/meDto";
import React, {
  createContext,
  FC,
  ReactNode,
  useContext,
  useMemo,
} from "react";

type PermContext = { permissions: string[]; permissionObjects?: Permission[] };
const PermissionContext = createContext<PermContext>({ permissions: [] });

interface PermissionProviderProps {
  permissions?: Permission[];
  children: ReactNode;
}

export const PermissionProvider: FC<PermissionProviderProps> = ({
  permissions,
  children,
}) => {
  const permissionKeys = useMemo(
    () => permissions?.map((p) => p.key),
    [permissions]
  );

  return (
    <PermissionContext.Provider value={{ permissions: permissionKeys || [],permissionObjects:permissions }}>
      {children}
    </PermissionContext.Provider>
  );
};

export const usePermissions = () => useContext(PermissionContext);
