import { getSession } from '@/lib/session'
import { isAdmin } from '@/lib/admin'
import { createVoteSite } from '@/lib/admin-votes'

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 name = String(b.name ?? '').trim()
  const url = String(b.url ?? '').trim()
  const imageUrl = String(b.imageUrl ?? '').trim()
  const points = Number(b.points)
  if (!name || !url || !(points >= 0)) return Response.json({ success: false, error: 'emptyError' })
  const id = await createVoteSite(name, url, imageUrl, points)
  return Response.json({ success: true, id })
}
