import { getSession } from '@/lib/session'
import { verifyTurnstile } from '@/lib/turnstile'
import { redeemTradeCode } from '@/lib/trade'

/** COMPRA: canjea un código de Comercio de PD. */
export async function POST(request: Request) {
  const session = await getSession()
  if (!session.accountId || !session.username) {
    return Response.json({ success: false, error: 'notAuthenticated' }, { status: 401 })
  }

  let body: Record<string, unknown> = {}
  try {
    body = await request.json()
  } catch {
    return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
  }

  const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || undefined
  const turnstileOk = await verifyTurnstile(String(body.turnstile ?? ''), ip)

  const result = await redeemTradeCode({
    buyerAccount: session.accountId,
    buyerEmail: session.bnetEmail || '',
    buyerCharacter: String(body.character ?? '').trim(),
    code: String(body.code ?? ''),
    password: String(body.password ?? ''),
    token: String(body.token ?? '').trim(),
    turnstileOk,
  })
  return Response.json(result)
}
