
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

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

  // 1. Get all distinct category strings from Product
  // Since groupBy might not be fully supported for string fields in some db versions in older prisma,
  // let's fetch all products and process in memory or use findMany distinct.
  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: {}, // Don't change existing if found
      create: {
        slug,
        nameEn: name,
        nameFr: name, // Default to English name, user can edit later
        image: null, 
      },
    });

    // Update products that have this category string but no categoryId
    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();
  });
