import prisma from '@/lib/prisma'
import { getVipServices } from '@/lib/vip-reseller'
import { calculateSellPrice, slugify } from '@/lib/utils'

export async function syncVipProducts(defaultMargin = 10) {
  console.log('[CRON] Starting VIP products sync...')
  try {
    const products = await getVipServices()
    let created = 0, updated = 0

    for (const product of products) {
      let category = await prisma.gameCategory.findFirst({ where: { name: product.game } })
      if (!category) {
        category = await prisma.gameCategory.create({
          data: { name: product.game, slug: slugify(product.game) },
        })
      }

      const basePrice = product.price.premium || product.price.basic
      const existing = await prisma.vipProduct.findUnique({ where: { providerCode: product.code } })

      if (existing) {
        await prisma.vipProduct.update({
          where: { providerCode: product.code },
          data: {
            price: basePrice,
            sellPrice: calculateSellPrice(basePrice, Number(existing.margin)),
            status: product.status === 'available',
            syncedAt: new Date(),
          },
        })
        updated++
      } else {
        await prisma.vipProduct.create({
          data: {
            providerCode: product.code,
            gameName: product.game,
            productName: product.name,
            price: basePrice,
            sellPrice: calculateSellPrice(basePrice, defaultMargin),
            margin: defaultMargin,
            description: product.description,
            status: product.status === 'available',
            categoryId: category.id,
            syncedAt: new Date(),
          },
        })
        created++
      }
    }

    console.log(`[CRON] VIP sync done: ${created} new, ${updated} updated`)
    return { created, updated }
  } catch (error) {
    console.error('[CRON] VIP sync failed:', error)
    throw error
  }
}
