/**
 * Backfill CaseKeyProgress from open_case transactions.
 * Run after: npx prisma db push
 *
 *   npm run db:backfill-case-keys --prefix server
 */
import { prisma } from '../src/db.js';
import { progressFromTotalOpens } from '../src/caseKeys.js';

async function main() {
  const txs = await prisma.transaction.findMany({
    where: { type: 'open_case' },
    select: { userId: true, meta: true },
    orderBy: { createdAt: 'asc' },
  });

  const counts = new Map();
  for (const tx of txs) {
    let meta;
    try {
      meta = JSON.parse(tx.meta || '{}');
    } catch {
      continue;
    }
    const caseId = Number(meta.caseId);
    if (!caseId) continue;
    const key = `${tx.userId}:${caseId}`;
    counts.set(key, (counts.get(key) || 0) + 1);
  }

  let upserted = 0;
  for (const [key, totalOpens] of counts) {
    const [userId, caseId] = key.split(':').map(Number);
    const { keys, opensSinceLastKey } = progressFromTotalOpens(totalOpens);

    await prisma.caseKeyProgress.upsert({
      where: { userId_caseId: { userId, caseId } },
      create: { userId, caseId, keys, opensSinceLastKey, totalOpens },
      update: { keys, opensSinceLastKey, totalOpens },
    });
    upserted += 1;
  }

  console.log(`Backfilled ${upserted} user/case key progress rows from ${txs.length} open_case transactions`);
}

main()
  .catch((err) => {
    console.error(err);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
