import { getSession } from '@/lib/session'
import { isAdmin } from '@/lib/admin'
import { createRecruitReward } from '@/lib/admin-recruit'

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 required_friends = Number(b.requiredFriends)
  const reward_name = String(b.rewardName ?? '').trim()
  const item_id = Number(b.itemId)
  const item_quantity = Number(b.itemQuantity) || 1
  const item_link = String(b.itemLink ?? '').trim()
  const icon_class = String(b.iconClass ?? '').trim()

  if (!(required_friends > 0) || !reward_name || !(item_id > 0)) {
    return Response.json({ success: false, error: 'emptyError' })
  }
  const id = await createRecruitReward({ required_friends, reward_name, item_id, item_quantity, item_link, icon_class })
  return Response.json({ success: true, id })
}
