import type { Metadata } from 'next'
import { headers } from 'next/headers'
import { setRequestLocale } from 'next-intl/server'
import { redirect } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getRealmName } from '@/lib/realm'
import { PageShell } from '@/components/PageShell'
import { DPointsTabs } from '@/components/DPointsTabs'

export const dynamic = 'force-dynamic'

export const metadata: Metadata = { title: 'Adquirir PD' }

export default async function DPointsPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params
  setRequestLocale(locale)

  const session = await getSession()
  if (!session.bnetId) redirect({ href: '/login', locale })
  if (!session.username) redirect({ href: '/select-account', locale })

  const realm = await getRealmName()
  const h = await headers()
  const ip = (h.get('x-forwarded-for') || '').split(',')[0].trim() || '0.0.0.0'
  const host = h.get('x-forwarded-host') || h.get('host') || ''
  const proto = h.get('x-forwarded-proto') || 'https'
  const origin = host ? `${proto}://${host}` : ''

  // Pasarelas automáticas: se habilitan al configurar sus credenciales por entorno.
  const paypalBusiness = process.env.PAYPAL_BUSINESS_EMAIL || ''

  return (
    <PageShell title="Adquirir PD">
      <DPointsTabs
        realm={realm}
        username={session.username!}
        ip={ip}
        locale={locale}
        origin={origin}
        paypalBusiness={paypalBusiness}
      />
    </PageShell>
  )
}
