// scripts/stripe-resync.ts — CLI over reconcileOrgSubscription: re-pull live
// Stripe subscriptions and write the plan/status/interval/period back to the DB,
// healing any drift from a missed `customer.subscription.updated` webhook.
//
//   bun --env-file=.env.local --conditions=react-server scripts/stripe-resync.ts            # all orgs
//   bun --env-file=.env.local --conditions=react-server scripts/stripe-resync.ts <orgId>    # one org
//
// (prod: --env-file=.env.production). Read-only against Stripe; only the DB writes.
import { reconcileOrgSubscription } from "@/lib/billing/reconcile";
import { subscription } from "@/lib/db/auth-schema";
import { db } from "@/lib/db/client";

const onlyOrg = process.argv[2];
const rows = await db
  .select({ referenceId: subscription.referenceId })
  .from(subscription);
const orgIds = [...new Set(rows.map((r) => r.referenceId))].filter(
  (id) => !onlyOrg || id === onlyOrg,
);

if (orgIds.length === 0) {
  console.log(
    onlyOrg ? `No subscription for org ${onlyOrg}` : "No subscriptions",
  );
  process.exit(0);
}

for (const orgId of orgIds) {
  try {
    const res = await reconcileOrgSubscription(orgId);
    if (!res) console.log(`  skip   ${orgId}: nothing to reconcile`);
    else
      console.log(
        `${res.changed ? "✓ FIXED" : "  ok   "} ${orgId}: ${res.fromPlan} → ${res.toPlan}/${res.status}`,
      );
  } catch (e) {
    console.log(`  err    ${orgId}: ${(e as Error).message}`);
  }
}
process.exit(0);
