/**
 * Backfill CatalogEntry from open_case transactions.
 * Run after: npx prisma db push
 *
 *   npm run db:backfill-catalog --prefix server
 */
import { prisma } from '../src/db.js';

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

  const pairs = new Map();
  for (const tx of txs) {
    let meta;
    try {
      meta = JSON.parse(tx.meta || '{}');
    } catch {
      continue;
    }
    const caseId = Number(meta.caseId);
    const itemId = Number(meta.itemId);
    if (!caseId || !itemId) continue;
    const key = `${tx.userId}:${caseId}:${itemId}`;
    if (!pairs.has(key)) {
      pairs.set(key, {
        userId: tx.userId,
        caseId,
        itemId,
        filledAt: tx.createdAt,
      });
    }
  }

  let created = 0;
  let skipped = 0;
  for (const row of pairs.values()) {
    try {
      await prisma.catalogEntry.create({
        data: {
          userId: row.userId,
          caseId: row.caseId,
          itemId: row.itemId,
          filledAt: row.filledAt,
        },
      });
      created += 1;
    } catch {
      skipped += 1;
    }
  }

  console.log(
    `Backfilled catalog: ${created} new entries, ${skipped} already present (${pairs.size} unique drops from ${txs.length} opens)`
  );
}

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