import { SubscriptionService } from "../services/subscription.service.js";
import { BILLING_REGISTRY } from "@nextsparkjs/registries/billing-registry";
async function checkDowngrade(teamId, targetPlanSlug) {
  const subscription = await SubscriptionService.getActive(teamId);
  if (!subscription) {
    return { canDowngrade: true, overLimits: [], warnings: [] };
  }
  const targetPlan = BILLING_REGISTRY.plans.find((p) => p.slug === targetPlanSlug);
  if (!targetPlan) {
    return { canDowngrade: false, overLimits: [], warnings: ["Target plan not found"] };
  }
  const overLimits = [];
  const warnings = [];
  for (const [limitSlug, newMax] of Object.entries(targetPlan.limits)) {
    if (newMax === -1) continue;
    const currentQuota = await SubscriptionService.checkQuota(teamId, limitSlug);
    if (currentQuota.current > newMax) {
      const limitConfig = BILLING_REGISTRY.limits[limitSlug];
      overLimits.push({
        limitSlug,
        limitName: (limitConfig == null ? void 0 : limitConfig.name) || limitSlug,
        current: currentQuota.current,
        newMax,
        excess: currentQuota.current - newMax
      });
    }
  }
  if (overLimits.length > 0) {
    warnings.push(
      "Some resources exceed new plan limits. Existing resources will remain accessible. You will not be able to create new ones until you are under the limit."
    );
  }
  return {
    canDowngrade: true,
    // Soft limit: always allow
    overLimits,
    warnings
  };
}
async function checkQuotaWithEnforcement(teamId, limitSlug) {
  const quota = await SubscriptionService.checkQuota(teamId, limitSlug);
  if (quota.allowed) {
    return { ...quota, enforced: false };
  }
  return {
    ...quota,
    allowed: false,
    enforced: true,
    enforcementReason: "over_limit_after_downgrade"
  };
}
export {
  checkDowngrade,
  checkQuotaWithEnforcement
};
