import { getSession } from '@/lib/session'
import { isAdmin } from '@/lib/admin'
import { createPromoCode } from '@/lib/admin-promo'

export async function POST(request: Request) {
  const session = await getSession()
  if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })
  let b: Record<string, unknown> = {}
  try {
    b = await request.json()
  } catch {
    return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
  }
  const code = String(b.code ?? '').trim()
  const pd = Number(b.pd)
  const pv = Number(b.pv)
  const maxUses = Number(b.maxUses)
  const expiresAt = String(b.expiresAt ?? '')
  if (!code || !Number.isInteger(pd) || pd < 0 || !Number.isInteger(pv) || pv < 0) {
    return Response.json({ success: false, error: 'emptyError' })
  }
  if (!Number.isInteger(maxUses) || maxUses < 1) return Response.json({ success: false, error: 'emptyError' })
  if (pd === 0 && pv === 0) return Response.json({ success: false, error: 'emptyError' })

  const r = await createPromoCode(code, pd, pv, maxUses, expiresAt)
  if (r.error) return Response.json({ success: false, error: r.error })
  return Response.json({ success: true, id: r.id })
}
