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

/** VENTA: crea 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 createTradeCode({
    creatorAccount: session.accountId,
    creatorEmail: session.bnetEmail || '',
    creatorCharacter: String(body.character ?? '').trim(),
    points: Number(body.points),
    gold: Number(body.gold),
    password: String(body.password ?? ''),
    token: String(body.token ?? '').trim(),
    turnstileOk,
  })
  return Response.json(result)
}
