import 'dotenv/config';
import { Prisma, PrismaClient } from '@prisma/client';
import { migrateDescriptionToPeriodEntries } from '../src/lib/milestonePeriods';

const prisma = new PrismaClient();

async function main() {
  const milestones = await prisma.milestone.findMany({
    where: {
      description: { not: null },
      NOT: { description: '' },
    },
    select: {
      id: true,
      title: true,
      description: true,
      startDate: true,
      dueDate: true,
      periodEntries: true,
    },
  });

  let migrated = 0;
  let skipped = 0;

  for (const m of milestones) {
    const { periodEntries, migrated: didMigrate } = migrateDescriptionToPeriodEntries({
      id: m.id,
      periodEntries: m.periodEntries,
      startDate: m.startDate,
      dueDate: m.dueDate,
      description: m.description,
    });

    if (!didMigrate || !periodEntries) {
      skipped += 1;
      continue;
    }

    await prisma.milestone.update({
      where: { id: m.id },
      data: {
        periodEntries: periodEntries as Prisma.InputJsonValue,
        description: null,
      },
    });
    migrated += 1;
    console.log(`  ✓ ${m.title} → 기간1 note (${periodEntries.length}건)`);
  }

  console.log(`\nDone. migrated=${migrated}, skipped=${skipped}, scanned=${milestones.length}`);
}

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