import { randomUUID } from 'crypto'
import { getSession } from '@/lib/session'
import { createCheckoutSession } from '@/lib/stripe'
import { createSumUpCheckout, sumupConfigured } from '@/lib/sumup'
import { PD_PER_UNIT, DP_MIN_AMOUNT, DP_MAX_AMOUNT } from '@/lib/dpoints'

/**
 * Inicia la compra de PD por Stripe o SumUp. El importe lo elige el usuario
 * (1 unidad = 100 PD). Devuelve la URL de checkout a la que redirigir.
 */
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 provider = String(body.provider ?? '')
  if (provider !== 'stripe' && provider !== 'sumup') {
    return Response.json({ success: false, error: 'invalidProvider' }, { status: 400 })
  }

  const amount = Number(body.amount)
  if (!Number.isInteger(amount) || amount < DP_MIN_AMOUNT || amount > DP_MAX_AMOUNT) {
    return Response.json({ success: false, error: 'invalidAmount' })
  }

  const points = amount * PD_PER_UNIT
  const site = process.env.SITE_URL || ''
  const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || '0.0.0.0'
  const currency = process.env.DP_CURRENCY || 'eur'

  if (provider === 'stripe') {
    const r = await createCheckoutSession({
      accountId: session.accountId,
      username: session.username,
      email: session.bnetEmail || '',
      acoreIp: ip,
      amount,
      currency,
      characterName: session.username,
      productName: `${points} PD`,
      successUrl: `${site}/d-points-success?provider=stripe`,
      cancelUrl: `${site}/d-points`,
      metadata: {
        service: 'dpoints',
        accountId: String(session.accountId),
        points: String(points),
        amount: String(amount),
      },
    })
    if (!r.success || !r.url) return Response.json({ success: false, error: 'stripeError' })
    return Response.json({ success: true, url: r.url })
  }

  // provider === 'sumup'
  if (!sumupConfigured()) return Response.json({ success: false, error: 'notConfigured' })
  const reference = randomUUID()
  const r = await createSumUpCheckout({
    accountId: session.accountId,
    username: session.username,
    email: session.bnetEmail || '',
    acoreIp: ip,
    amount,
    points,
    reference,
    description: `${points} PD`,
    returnUrl: `${site}/d-points-success?provider=sumup&ref=${reference}`,
  })
  if (!r.success || !r.url) return Response.json({ success: false, error: r.error || 'sumupError' })
  return Response.json({ success: true, url: r.url })
}
