import { getTranslations, setRequestLocale } from 'next-intl/server'
import { Link } from '@/i18n/navigation'
import { fulfillCheckoutSession } from '@/lib/fulfill'
import { isSessionPaid } from '@/lib/stripe'

export const dynamic = 'force-dynamic'

export default async function BattlepaySuccessPage({
  params,
  searchParams,
}: {
  params: Promise<{ locale: string }>
  searchParams: Promise<{ session_id?: string }>
}) {
  const { locale } = await params
  setRequestLocale(locale)
  const { session_id } = await searchParams
  const t = await getTranslations('Battlepay')

  // Entrega compartida con el webhook (marca la orden PAID; idempotente).
  let status: 'paid' | 'already' | 'error' = 'error'
  if (session_id) {
    const r = await fulfillCheckoutSession(session_id)
    if (r.ok) status = 'paid'
    else if (await isSessionPaid(session_id)) status = 'already'
  }

  return (
    <main className="mx-auto max-w-lg px-4 py-12 text-center">
      <h1 className="mb-6 text-2xl font-bold text-amber-500">{t('title')}</h1>
      {status === 'paid' ? (
        <p className="text-green-400">{t('paidOk')}</p>
      ) : status === 'already' ? (
        <p className="text-green-400">{t('alreadyPaid')}</p>
      ) : (
        <p className="text-red-400">{t('genericError')}</p>
      )}
      <p className="mt-6">
        <Link href="/battlepay" className="text-sky-400 hover:underline">
          ← {t('backToStore')}
        </Link>
      </p>
    </main>
  )
}
