"use client";

import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTenantId } from "@/hooks/useTenantId";
import { paymentApi } from "@/modules/payment/services/payment-api";

type MembershipLike = { tenant_id?: string; permissions?: string[] };

export function usePaymentPermissions() {
  const { tenantId, me } = useTenantId();
  const catalog = useQuery({
    queryKey: ["payment", tenantId, "permissions-catalog"],
    queryFn: () => paymentApi.permissions.catalog(tenantId!),
    enabled: !!tenantId,
    staleTime: 60_000,
  });
  const membership = (me?.memberships as MembershipLike[] | undefined)?.find(
    (m) => m.tenant_id === tenantId
  );
  const userPerms = useMemo(() => new Set(membership?.permissions ?? []), [membership]);

  function can(permission: string) {
    if (userPerms.size === 0) return true;
    if (userPerms.has("payment.manage") || userPerms.has("*")) return true;
    return userPerms.has(permission);
  }

  return { catalog, can, tenantId };
}
