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

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

  const { searchParams } = new URL(req.url)
  const category = searchParams.get('category')

  const where = category ? { category } : {}

  try {
    const products = await prisma.smmProduct.findMany({
      where,
      orderBy: { category: 'asc' }
    })
    return NextResponse.json(products)
  } catch (error) {
    return NextResponse.json({ error: 'Gagal mengambil data produk' }, { status: 500 })
  }
}

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

  try {
    const { id, margin, isActive } = await req.json()
    
    if (!id) return NextResponse.json({ error: 'ID is required' }, { status: 400 })

    const existing = await prisma.smmProduct.findUnique({ where: { id } })
    if (!existing) return NextResponse.json({ error: 'Produk tidak ditemukan' }, { status: 404 })

    const updateData: any = {}
    
    if (typeof isActive === 'boolean') {
      updateData.isActive = isActive
    }

    if (margin !== undefined) {
      const newMargin = Number(margin)
      updateData.margin = newMargin
      updateData.sellPrice = Number(existing.price) + (Number(existing.price) * newMargin / 100)
    }

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

    return NextResponse.json({ success: true, product: updated })
  } catch (error: any) {
    return NextResponse.json({ error: error.message || 'Gagal update produk' }, { status: 500 })
  }
}
