import { db } from '@/lib/db'
import { seedCategories, seedProducts, seedKits } from '@/lib/catalog-data'

export async function seedDatabase() {
  console.log('🌱 Seeding database...')

  // Clear existing data
  await db.favorite.deleteMany()
  await db.kit.deleteMany()
  await db.product.deleteMany()
  await db.category.deleteMany()

  // Insert categories
  for (const cat of seedCategories) {
    await db.category.create({
      data: {
        name: cat.name,
        slug: cat.slug,
        description: cat.description,
        icon: cat.icon,
        color: cat.color,
        order: cat.order,
      },
    })
  }
  console.log(`✅ Inserted ${seedCategories.length} categories`)

  // Insert products
  const categories = await db.category.findMany()
  const catMap = new Map(categories.map(c => [c.slug, c.id]))

  for (const prod of seedProducts) {
    const categoryId = catMap.get(prod.categorySlug)
    if (!categoryId) {
      console.warn(`Category not found for ${prod.name}: ${prod.categorySlug}`)
      continue
    }
    await db.product.create({
      data: {
        name: prod.name,
        code: prod.code,
        slug: prod.slug,
        description: prod.description,
        benefits: prod.benefits,
        ingredients: prod.ingredients,
        volume: prod.volume,
        fragrance: prod.fragrance || null,
        activeIngredient: prod.activeIngredient || null,
        price: prod.price,
        promotionalPrice: prod.promotionalPrice || null,
        discountPercent: prod.discountPercent || null,
        page: prod.page,
        isLaunch: prod.isLaunch || false,
        isBestseller: prod.isBestseller || false,
        isLowerPriceYear: prod.isLowerPriceYear || false,
        isKit: prod.isKit || false,
        isCombo: prod.isCombo || false,
        categoryId,
      },
    })
  }
  console.log(`✅ Inserted ${seedProducts.length} products`)

  // Insert kits
  for (const kit of seedKits) {
    await db.kit.create({
      data: {
        name: kit.name,
        code: kit.code,
        description: kit.description,
        price: kit.price,
        promotionalPrice: kit.promotionalPrice,
        discountPercent: kit.discountPercent,
        page: kit.page,
        savings: kit.savings,
      },
    })
  }
  console.log(`✅ Inserted ${seedKits.length} kits`)

  console.log('🎉 Seeding complete!')
}

// Run if called directly
seedDatabase()
  .catch(console.error)
  .finally(() => db.$disconnect())
