// src/lib/billing/stripe-events.ts — dispatcher for the Stripe plugin's
// generic `onEvent` webhook hook (src/lib/auth.ts). The plugin invokes it for
// EVERY verified Stripe event, AFTER its own subscription handlers ran (so the
// `subscription` row already reflects the new plan). Each handler filters to
// the event types it cares about and ignores the rest.
import "server-only";
import type Stripe from "stripe";
import { fulfillMcpPack } from "./pack-fulfillment";
import { unblockSeatInvitations } from "./seat-unblock";
import { syncSerankingByokAddon } from "./seranking-addon";
import { fulfillSerankingPack } from "./seranking-fulfillment";
import { syncSubscriptionFromEvent } from "./subscription-sync";

/** Fan a verified Stripe webhook event out to every app-level handler. */
export async function handleStripeEvent(event: Stripe.Event): Promise<void> {
  // MCP credit packs — one-off `checkout.session.completed` purchases (3C).
  await fulfillMcpPack(event);
  // SE-Ranking sync packs — one-off `checkout.session.completed` purchases
  // (monétisation slice 2).
  await fulfillSerankingPack(event);
  // SE-Ranking BYO-key add-on — `customer.subscription.*` lifecycle events.
  await syncSerankingByokAddon(event);
  // Seat flow S3 — `customer.subscription.created/updated` plan upgrades free
  // seats for invitees blocked at acceptance.
  await unblockSeatInvitations(event);
  // Refresh the renew date / period state on every subscription event so it's
  // updated immediately, not only when someone opens the billing page.
  await syncSubscriptionFromEvent(event);
}
