import { getSession } from '@/lib/session'
import { claimRecruitReward } from '@/lib/recruit-claim'

export async function POST(request: Request) {
  const session = await getSession()
  if (!session.accountId || !session.username) {
    return Response.json({ success: false, message: 'notAuthenticated' }, { status: 401 })
  }

  let b: Record<string, unknown> = {}
  try { b = await request.json() } catch { return Response.json({ success: false, message: 'invalidRequest' }, { status: 400 }) }
  const rewardId = Number(b.rewardId)
  const character = String(b.character ?? '').trim()
  if (!rewardId || !character) return Response.json({ success: false, message: 'selectRewardAndCharacter' })

  const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || '127.0.0.1'
  const result = await claimRecruitReward(session.accountId, session.username, rewardId, character, ip)
  return Response.json(result)
}
