import { getSession } from '@/lib/session'
import { isAdmin } from '@/lib/admin'
import { updatePromoCode, deletePromoCode } from '@/lib/admin-promo'

export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })
  const { id } = await params
  let b: Record<string, unknown> = {}
  try {
    b = await request.json()
  } catch {
    return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
  }
  const pd = Number(b.pd)
  const pv = Number(b.pv)
  const maxUses = Number(b.maxUses)
  if (!Number.isInteger(pd) || pd < 0 || !Number.isInteger(pv) || pv < 0 || !Number.isInteger(maxUses) || maxUses < 1) {
    return Response.json({ success: false, error: 'emptyError' })
  }
  await updatePromoCode(Number(id), { pd, pv, maxUses, active: Boolean(b.active) })
  return Response.json({ success: true })
}

export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })
  const { id } = await params
  await deletePromoCode(Number(id))
  return Response.json({ success: true })
}
