"use client";

import { useQuery } from "@tanstack/react-query";
import { useTenantId } from "@/hooks/useTenantId";
import { useMe } from "@/hooks/useMe";
import { deliveryApi } from "@/modules/delivery/services/delivery-api";

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

  const catalogQ = useQuery({
    queryKey: ["delivery", tenantId, "permissions-catalog"],
    queryFn: () => deliveryApi.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 === "delivery.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("delivery.manage");
  };

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