// One-off cleanup: when we migrated to Stripe Billing, any pre-existing
// Subscription rows that have no `stripeSubscriptionId` are legacy from the
// one-time-payment flow. If the same user now has a Stripe-backed sub,
// the legacy row is a duplicate that confuses `getMySubscription` and
// the UI. We mark every "active" legacy row as `cancelled` so Stripe is
// the only source of truth going forward.
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

(async () => {
  // Find users who have both: a Stripe-backed sub + a legacy active sub.
  const usersWithStripeSubs = await prisma.subscription.findMany({
    where: { stripeSubscriptionId: { not: null }, status: { in: ['active', 'trialing', 'past_due'] } },
    select: { userId: true },
    distinct: ['userId'],
  });

  const userIds = usersWithStripeSubs.map((s) => s.userId);
  if (userIds.length === 0) {
    console.log('No Stripe-backed subs found; nothing to clean.');
    await prisma.$disconnect();
    return;
  }

  // For those users, every active/pending row WITHOUT a stripeSubscriptionId
  // is stale. Flip to cancelled so getMySubscription returns the Stripe one.
  const result = await prisma.subscription.updateMany({
    where: {
      userId: { in: userIds },
      stripeSubscriptionId: null,
      status: { in: ['active', 'pending', 'trialing'] },
    },
    data: { status: 'cancelled', cancelAt: new Date() },
  });

  console.log(`Cleaned ${result.count} stale legacy subscription row(s).`);
  await prisma.$disconnect();
})();
