"use client";

import { useQuery } from "@tanstack/react-query";
import { useTenantId } from "@/hooks/useTenantId";
import { useMe } from "@/hooks/useMe";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";

/** Permission checks — backend is authoritative; owner gets full access in UI. */
export function useHealthcarePermissions() {
  const { tenantId } = useTenantId();
  const { me } = useMe();

  const catalogQ = useQuery({
    queryKey: ["healthcare", tenantId, "permissions-catalog"],
    queryFn: () => healthcareApi.permissions.catalog(tenantId!),
    enabled: !!tenantId,
    staleTime: 5 * 60_000,
  });

  const membership = me?.memberships.find((m) => m.tenant_id === tenantId);
  const isOwner = membership?.is_owner ?? false;
  const isPlatformAdmin = me?.platform_role === "platform_admin";

  const can = (permission?: string) => {
    if (!permission) return true;
    if (isOwner || isPlatformAdmin) return true;
    if (permission.endsWith(".view") || permission === "healthcare.view") return !!tenantId;
    return false;
  };

  const canManage = (viewPerm?: string, managePerm?: string) => {
    if (isOwner || isPlatformAdmin) return true;
    if (managePerm) return can(managePerm);
    if (viewPerm) return can(viewPerm.replace(".view", ".manage"));
    return can("healthcare.manage");
  };

  return {
    can,
    canManage,
    isOwner,
    catalog: catalogQ.data,
    isLoading: catalogQ.isLoading,
  };
}
