"use client";

import { useQuery } from "@tanstack/react-query";
import { api } from "@/lib/api";
import type { UserInfo } from "@/lib/types";

export function usePermissions() {
  const { data, isLoading } = useQuery({
    queryKey: ["me"],
    queryFn: () => api.get<UserInfo>("/me"),
    staleTime: 60 * 1000,
  });

  const role = data?.role ?? null;
  const permissions = data?.permissions ?? [];

  function can(permission: string): boolean {
    return permissions.includes(permission);
  }

  return {
    role,
    permissions,
    can,
    isLoading,
    userId: data?.user_id ?? null,
    tenantId: data?.tenant_id ?? null,
    isDemo: data?.is_demo ?? false,
  };
}
