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

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 (
    <PageShell title={t('title')}>
      <div className="box-content">
        <div className="body-box-content centered">
          {status === 'paid' ? (
            <span className="ok-form-response">{t('paidOk')}</span>
          ) : status === 'already' ? (
            <span className="ok-form-response">{t('alreadyPaid')}</span>
          ) : (
            <span className="red-form-response">{t('genericError')}</span>
          )}
          <br />
          <br />
          <p>
            <Link href="/battlepay">← {t('backToStore')}</Link>
          </p>
        </div>
      </div>
    </PageShell>
  )
}
