import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import prisma from '@/lib/prisma'
import { authOptions } from '@/lib/auth'
import { slugify } from '@/lib/utils'

export const dynamic = 'force-dynamic'

export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const session = await getServerSession(authOptions)
    if (session?.user?.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    const { id } = params
    const body = await req.json()
    
    const updateData: any = {}
    if (body.name !== undefined) {
      updateData.name = body.name
      updateData.slug = slugify(body.name)
    }
    if (body.thumbnail !== undefined) updateData.thumbnail = body.thumbnail
    if (body.banner !== undefined) updateData.banner = body.banner
    if (body.isActive !== undefined) updateData.isActive = body.isActive
    if (body.sortOrder !== undefined) updateData.sortOrder = parseInt(body.sortOrder)
    if (body.fieldConfig !== undefined) updateData.fieldConfig = body.fieldConfig

    const category = await prisma.gameCategory.update({
      where: { id },
      data: updateData,
    })

    return NextResponse.json({ success: true, category })
  } catch (error: any) {
    console.error('[ADMIN CATEGORY PATCH]', error)
    if (error.code === 'P2002') {
      return NextResponse.json({ error: 'Nama kategori sudah ada' }, { status: 400 })
    }
    return NextResponse.json({ error: 'Gagal update kategori' }, { status: 500 })
  }
}

export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const session = await getServerSession(authOptions)
    if (session?.user?.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    const { id } = params

    // Check if category has products
    const productsCount = await prisma.vipProduct.count({ where: { categoryId: id } })
    if (productsCount > 0) {
      return NextResponse.json({ error: `Tidak bisa menghapus kategori karena masih memiliki ${productsCount} produk. Pindahkan produk terlebih dahulu.` }, { status: 400 })
    }

    await prisma.gameCategory.delete({
      where: { id },
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('[ADMIN CATEGORY DELETE]', error)
    return NextResponse.json({ error: 'Gagal menghapus kategori' }, { status: 500 })
  }
}
