import Stripe from "stripe";
import { BILLING_REGISTRY } from "@nextsparkjs/registries/billing-registry";
let stripeInstance = null;
function getStripe() {
  if (!stripeInstance) {
    if (!process.env.STRIPE_SECRET_KEY) {
      throw new Error("STRIPE_SECRET_KEY is not configured");
    }
    stripeInstance = new Stripe(process.env.STRIPE_SECRET_KEY, {
      apiVersion: "2025-08-27.basil",
      typescript: true
    });
  }
  return stripeInstance;
}
async function createCheckoutSession(params) {
  const { teamId, planSlug, billingPeriod, successUrl, cancelUrl, customerEmail, customerId } = params;
  const planConfig = BILLING_REGISTRY.plans.find((p) => p.slug === planSlug);
  if (!planConfig) {
    throw new Error(`Plan ${planSlug} not found in BILLING_REGISTRY`);
  }
  const priceId = billingPeriod === "yearly" ? planConfig.stripePriceIdYearly : planConfig.stripePriceIdMonthly;
  if (!priceId) {
    throw new Error(`No Stripe price configured for ${planSlug} ${billingPeriod}`);
  }
  const sessionParams = {
    mode: "subscription",
    payment_method_types: ["card"],
    line_items: [{ price: priceId, quantity: 1 }],
    success_url: successUrl,
    cancel_url: cancelUrl,
    metadata: { teamId, planSlug, billingPeriod },
    client_reference_id: teamId
  };
  if (customerId) {
    sessionParams.customer = customerId;
  } else if (customerEmail) {
    sessionParams.customer_email = customerEmail;
  }
  if (planConfig.trialDays && planConfig.trialDays > 0 && !customerId) {
    sessionParams.subscription_data = {
      trial_period_days: planConfig.trialDays
    };
  }
  return getStripe().checkout.sessions.create(sessionParams);
}
async function createPortalSession(params) {
  return getStripe().billingPortal.sessions.create({
    customer: params.customerId,
    return_url: params.returnUrl
  });
}
function verifyWebhookSignature(payload, signature) {
  const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
  if (!webhookSecret) {
    throw new Error("STRIPE_WEBHOOK_SECRET is not configured");
  }
  return getStripe().webhooks.constructEvent(payload, signature, webhookSecret);
}
async function getCustomer(customerId) {
  return getStripe().customers.retrieve(customerId);
}
async function createCustomer(params) {
  return getStripe().customers.create(params);
}
function getStripeInstance() {
  return getStripe();
}
async function cancelSubscriptionAtPeriodEnd(subscriptionId) {
  return getStripe().subscriptions.update(subscriptionId, {
    cancel_at_period_end: true
  });
}
async function cancelSubscriptionImmediately(subscriptionId) {
  return getStripe().subscriptions.cancel(subscriptionId);
}
async function reactivateSubscription(subscriptionId) {
  return getStripe().subscriptions.update(subscriptionId, {
    cancel_at_period_end: false
  });
}
async function updateSubscriptionPlan(params) {
  var _a;
  const { subscriptionId, newPriceId, prorationBehavior = "create_prorations" } = params;
  const stripe = getStripe();
  const subscription = await stripe.subscriptions.retrieve(subscriptionId);
  const itemId = (_a = subscription.items.data[0]) == null ? void 0 : _a.id;
  if (!itemId) {
    throw new Error("Subscription has no items");
  }
  return stripe.subscriptions.update(subscriptionId, {
    items: [{
      id: itemId,
      price: newPriceId
    }],
    proration_behavior: prorationBehavior
  });
}
export {
  cancelSubscriptionAtPeriodEnd,
  cancelSubscriptionImmediately,
  createCheckoutSession,
  createCustomer,
  createPortalSession,
  getCustomer,
  getStripeInstance,
  reactivateSubscription,
  updateSubscriptionPlan,
  verifyWebhookSignature
};
