import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getVipNickname } from '@/lib/vip-reseller'

// GET products for a specific game (by category slug)
export async function GET(
  req: NextRequest,
  { params }: { params: { slug: string } }
) {
  try {
    const category = await prisma.gameCategory.findUnique({
      where: { slug: params.slug, isActive: true },
    })

    if (!category) {
      return NextResponse.json({ error: 'Game tidak ditemukan' }, { status: 404 })
    }

    const products = await prisma.vipProduct.findMany({
      where: {
        categoryId: category.id,
        isActive: true,
        status: true,
      },
      orderBy: { sellPrice: 'asc' },
    })

    return NextResponse.json({ category, products })
  } catch (error) {
    console.error('[GAME PRODUCTS]', error)
    return NextResponse.json({ error: 'Gagal memuat produk' }, { status: 500 })
  }
}

// POST - validate nickname
export async function POST(
  req: NextRequest,
  { params }: { params: { slug: string } }
) {
  try {
    const { code, targetId, zone } = await req.json()
    if (!code || !targetId) {
      return NextResponse.json({ error: 'Kode produk dan ID tujuan diperlukan' }, { status: 400 })
    }

    const result = await getVipNickname(code, targetId, zone)
    return NextResponse.json({ nickname: result.nickname, country: result.country })
  } catch (error: any) {
    return NextResponse.json({ error: error.message || 'ID tidak valid' }, { status: 400 })
  }
}
