import { getSession } from '@/lib/session'
import { getPendingOrder } from '@/lib/battlepay'
import { createCheckoutSession } from '@/lib/stripe'

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

  let b: Record<string, string> = {}
  try { b = await request.json() } catch { return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 }) }
  const reference = String(b.reference ?? '').trim()
  if (!reference) return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })

  const order = await getPendingOrder(reference, session.accountId)
  if (!order) return Response.json({ success: false, error: 'orderNotFound' })
  if (!(order.price_eur > 0)) return Response.json({ success: false, error: 'invalidRequest' })

  const site = process.env.SITE_URL || ''
  const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || '0.0.0.0'

  const r = await createCheckoutSession({
    accountId: session.accountId,
    username: session.username || '',
    email: session.bnetEmail || '',
    acoreIp: ip,
    amount: order.price_eur,
    characterName: reference, // en battlepay guardamos la referencia como identificador
    productName: order.product_name,
    successUrl: `${site}/battlepay-success`,
    cancelUrl: `${site}/battlepay`,
    metadata: { battlepay_reference: reference },
  })
  if (!r.success || !r.url) return Response.json({ success: false, error: 'stripeError' })
  return Response.json({ success: true, url: r.url })
}
