import { PrismaClient } from "@prisma/client";
import { parseProductContext } from "../lib/types/product-context";

const prisma = new PrismaClient();

async function main() {
  const topics = await prisma.topic.findMany({
    where: {
      topicGoal: "placement",
      productContext: { not: null },
      productProfileId: null,
    },
  });

  for (const topic of topics) {
    const fields = parseProductContext(topic.productContext);
    const label =
      [fields.brand, fields.product].filter(Boolean).join(" · ") || topic.label;

    const profile = await prisma.productProfile.create({
      data: {
        accountId: topic.accountId,
        label,
        context: topic.productContext!,
      },
    });

    await prisma.topic.update({
      where: { id: topic.id },
      data: { productProfileId: profile.id },
    });

    console.log(`Migrated topic "${topic.label}" → profile "${label}"`);
  }

  console.log(`Done. Migrated ${topics.length} profile(s).`);
}

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