import { PrismaClient } from '@prisma/client';
import fs from 'fs';
import path from 'path';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();
const productsPath = path.join(process.cwd(), 'prisma/products_data.json');
const products = JSON.parse(fs.readFileSync(productsPath, 'utf8'));

async function main() {
  console.log('Starting seed...');
  
  // 1. Clean up database
  console.log('Cleaning up database...');
  await prisma.orderItem.deleteMany({});
  await prisma.productVariant.deleteMany({});
  await prisma.product.deleteMany({});
  await prisma.category.deleteMany({});
  await prisma.user.deleteMany({});

  // 2. Create Admin User
  console.log('Creating admin user...');
  const hashedPassword = await bcrypt.hash('Admin123!', 10);
  await prisma.user.create({
    data: {
      name: 'Admin User',
      email: 'admin@musafoods.com',
      password: hashedPassword,
      role: 'ADMIN',
    },
  });

  // 3. Seed Products
  console.log(`Seeding ${products.length} products...`);
  for (const product of products) {
    const slug = product.slug || product.nameEn.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)+/g, '');
    
    // Create Product
    await prisma.product.create({
      data: {
        id: product.id,
        nameEn: product.nameEn,
        nameFr: product.nameFr,
        slug: slug as any,
        descriptionEn: product.descriptionEn,
        descriptionFr: product.descriptionFr,
        category: product.category,
        image: product.image,
        unit: product.unit,
        minOrder: product.minOrder,
        origin: product.origin,
        featured: product.featured,
        variants: {
            create: product.variants?.map((v: any) => ({
                id: v.id,
                size: v.size,
                sku: v.sku
            })) || []
        }
      },
    });
  }

  // 4. Reconcile Categories
  console.log('Reconciling categories...');

  const categoryImages: Record<string, string> = {
    rice: 'https://musafoods.ca/wp-content/uploads/2024/05/1-2-300x300.png',
    beans: 'https://musafoods.ca/wp-content/uploads/2024/05/2-3-300x300.png',
    seasonings: 'https://musafoods.ca/wp-content/uploads/2024/05/3-3-300x300.png',
    haitian: 'https://musafoods.ca/wp-content/uploads/2024/05/6-1-300x300.png',
    semolina: 'https://musafoods.ca/wp-content/uploads/2024/05/ICE-1-300x300.png',
    wheat_oat: 'https://musafoods.ca/wp-content/uploads/2024/05/5-2-300x300.png',
    dry_fish: 'https://musafoods.ca/wp-content/uploads/2024/05/7-1-300x300.png',
    corn_meal: 'https://musafoods.ca/wp-content/uploads/2024/05/8-1-300x300.png',
    detergent: 'https://musafoods.ca/wp-content/uploads/2024/05/15-1-300x300.png',
  };

  // Fetch all products to get unique category strings
  const allProducts = await prisma.product.findMany({
    select: { id: true, category: true },
  });

  const uniqueCategories = new Set(allProducts.map(p => p.category));
  console.log(`Found ${uniqueCategories.size} unique categories.`);

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

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

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

    // Create Category
    const category = await prisma.category.create({
      data: {
        slug,
        nameEn: name,
        nameFr: name, // Default to English name
        image: image,
      },
    });

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

  // 5. Seed Email Settings
  console.log('Seeding email settings...');
  const emailSettings = [
    { key: 'smtp_host', value: 'mail.clarobyte.com' },
    { key: 'smtp_port', value: '465' },
    { key: 'smtp_user', value: 'musafoods@clarobyte.com' },
    { key: 'smtp_pass', value: '3[+Vge9{T1PzM{No' },
    { key: 'smtp_from', value: 'MusaFoods <musafoods@clarobyte.com>' },
    { key: 'admin_emails', value: 'musafoods@clarobyte.com, saichandvaranasi1716@gmail.com' }
  ];

  for (const setting of emailSettings) {
    await prisma.systemSetting.upsert({
      where: { key: setting.key },
      update: {}, // Don't overwrite if existing, to preserve manual changes
      create: { key: setting.key, value: setting.value },
    });
  }

  console.log('Seed completed successfully.');
}

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