import { NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'
import { getZaynflazzServices } from '@/lib/zaynflazz'

export async function POST() {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  try {
    const services = await getZaynflazzServices()
    if (!services || services.length === 0) {
      return NextResponse.json({ error: 'Tidak ada data layanan dari provider' }, { status: 400 })
    }

    let syncedCount = 0

    // Typical default margin for new SMM services (e.g., 10%)
    const defaultMargin = 10

    for (const srv of services) {
      const originalPrice = Number(srv.harga)
      
      const existing = await prisma.smmProduct.findUnique({
        where: { serviceId: srv.sid.toString() }
      })

      if (existing) {
        // Update existing (keep existing margin/sellPrice, only update base info if needed)
        // Wait, if original price changed, we should recalculate sellPrice based on existing margin
        const newSellPrice = originalPrice + (originalPrice * Number(existing.margin) / 100)

        await prisma.smmProduct.update({
          where: { id: existing.id },
          data: {
            category: srv.kategori,
            name: srv.layanan,
            minOrder: Number(srv.min),
            maxOrder: Number(srv.max),
            price: originalPrice,
            sellPrice: newSellPrice,
            description: srv.catatan,
            averageTime: srv.average,
            isRefill: srv.refill === 'true',
          }
        })
      } else {
        // Create new
        const sellPrice = originalPrice + (originalPrice * defaultMargin / 100)
        
        await prisma.smmProduct.create({
          data: {
            serviceId: srv.sid.toString(),
            category: srv.kategori,
            name: srv.layanan,
            minOrder: Number(srv.min),
            maxOrder: Number(srv.max),
            price: originalPrice,
            sellPrice: sellPrice,
            margin: defaultMargin,
            description: srv.catatan,
            averageTime: srv.average,
            isRefill: srv.refill === 'true',
            isActive: true, // Auto active on first sync
          }
        })
      }
      syncedCount++
    }

    return NextResponse.json({ success: true, count: syncedCount })
  } catch (error: any) {
    console.error('[SYNC SMM ERROR]', error)
    return NextResponse.json({ error: error.message || 'Terjadi kesalahan saat sinkronisasi' }, { status: 500 })
  }
}
