
const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

async function main() {
  console.log('Starting category reconciliation...');

  // 1. Get all products
  const products = await prisma.product.findMany({
    select: { id: true, category: true, categoryId: true },
  });

  const uniqueCategories = new Set(products.map(p => p.category));

  console.log(`Found ${uniqueCategories.size} unique categories.`);

  for (const catString of uniqueCategories) {
    if (!catString) continue;

    const slug = catString.toLowerCase().replace(/[^a-z0-9]+/g, '_');
    const name = catString.charAt(0).toUpperCase() + catString.slice(1).replace(/_/g, ' ');

    console.log(`Processing category: ${catString} -> ${slug} (${name})`);

    // Upsert Category
    const category = await prisma.category.upsert({
      where: { slug },
      update: {}, 
      create: {
        slug,
        nameEn: name,
        nameFr: name, 
        image: null, 
      },
    });

    // Update products
    await prisma.product.updateMany({
      where: { 
        category: catString,
        categoryId: null 
      },
      data: {
        categoryId: category.id
      }
    });
  }

  console.log('Category reconciliation complete.');
}

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