"use client";
import useSWR from "swr";

type Resource = "BOARD" | "POST" | "COMMENT" | "USER" | "ADMIN";
type Action = "READ" | "CREATE" | "UPDATE" | "DELETE" | "MODERATE" | "ADMINISTER";

const fetcher = (url: string) => fetch(url).then((r) => r.json());

export function usePermission() {
  const { data } = useSWR<{ permissions: { resource: Resource; action: Action }[] }>(
    "/api/auth/permissions",
    fetcher
  );
  const perms = data?.permissions ?? [];
  function can(resource: Resource, action: Action) {
    return (
      perms.some((p) => p.resource === "ADMIN" && p.action === "ADMINISTER") ||
      perms.some((p) => p.resource === resource && p.action === action)
    );
  }
  return { can };
}


