const fs = require('node:fs');
const path = require('node:path');
const Papa = require('papaparse');
const { PrismaClient } = require('../app/generated/prisma');

async function main() {
  const prisma = new PrismaClient();
  const csvPath = path.resolve(process.cwd(), 'datas/contents.csv');
  const csv = fs.readFileSync(csvPath, 'utf8');
  const parsed = Papa.parse(csv, { header: true, skipEmptyLines: true });
  if (parsed.errors && parsed.errors.length) {
    console.error(parsed.errors);
    process.exit(1);
  }

  for (const r of parsed.data) {
    if (!r.Id) continue;
    const pubDate = new Date(r.pubDate);
    const views = Number(r.views ?? 0);
    const validViews = Number(r.validViews ?? 0);
    const premiumViews = Number(r.premiumViews ?? 0);
    const watchTime = Math.round(Number(r.watchTime ?? 0));

    await prisma.content.upsert({
      where: { id: r.Id },
      update: {
        subject: r.subject,
        pubDate,
        views,
        validViews,
        premiumViews,
        watchTime,
      },
      create: {
        id: r.Id,
        subject: r.subject,
        pubDate,
        views,
        validViews,
        premiumViews,
        watchTime,
      },
    });
  }
  await prisma.$disconnect();
  console.log('Seeded contents from CSV');
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});


