import { useSubscription } from "./useSubscription";
import { BILLING_REGISTRY } from "@nextsparkjs/registries/billing-registry";
function useMembership() {
  const subscriptionContext = useSubscription();
  return {
    // Subscription info
    plan: subscriptionContext.plan,
    subscription: subscriptionContext.subscription,
    status: subscriptionContext.status,
    isTrialing: subscriptionContext.isTrialing,
    isActive: subscriptionContext.isActive,
    isPastDue: subscriptionContext.isPastDue,
    isCanceled: subscriptionContext.isCanceled,
    isLoading: subscriptionContext.isLoading,
    // Feature check (FIX2: No hook calls, uses cached features)
    hasFeature: (featureSlug) => {
      if (subscriptionContext.features.includes("*")) return true;
      return subscriptionContext.features.includes(featureSlug);
    },
    // Quota check (FIX2: Returns sync cached data)
    getQuota: (limitSlug) => {
      const limitInfo = subscriptionContext.limits[limitSlug];
      if (!limitInfo) return null;
      return {
        max: limitInfo.max,
        resetPeriod: limitInfo.resetPeriod
      };
    },
    // NEW: Async version for full quota info with current usage
    getQuotaAsync: async (limitSlug) => {
      var _a;
      if (!((_a = subscriptionContext.subscription) == null ? void 0 : _a.teamId)) return null;
      try {
        const response = await fetch(
          `/api/v1/teams/${subscriptionContext.subscription.teamId}/usage/${limitSlug}`
        );
        if (!response.ok) return null;
        const data = await response.json();
        return data.data;
      } catch (error) {
        console.error("Error fetching quota:", error);
        return null;
      }
    },
    // Unified permission check (Permission + Feature + Quota)
    canDo: async (action) => {
      var _a, _b, _c;
      try {
        const permissionMapping = (_a = BILLING_REGISTRY.actionMappings.permissions) == null ? void 0 : _a[action];
        const featureMapping = (_b = BILLING_REGISTRY.actionMappings.features) == null ? void 0 : _b[action];
        const limitMapping = (_c = BILLING_REGISTRY.actionMappings.limits) == null ? void 0 : _c[action];
        if (!permissionMapping && !featureMapping && !limitMapping) {
          return { allowed: true };
        }
        const response = await fetch("/api/v1/billing/check-action", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ action })
        });
        if (!response.ok) {
          return { allowed: false, reason: "Failed to check action permission" };
        }
        const data = await response.json();
        return data.data;
      } catch (error) {
        console.error("Error checking action:", error);
        return { allowed: false, reason: "Error checking permission" };
      }
    },
    // Refresh subscription data
    refetch: subscriptionContext.refetch
  };
}
export {
  useMembership
};
