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

export const dynamic = 'force-dynamic'

export default async function ServiceSuccessPage({
  params,
  searchParams,
}: {
  params: Promise<{ locale: string }>
  searchParams: Promise<{ service?: string; session_id?: string; provider?: string; ref?: string }>
}) {
  const { locale } = await params
  setRequestLocale(locale)
  const { service: urlService, session_id, provider, ref } = await searchParams
  const t = await getTranslations('Paid')

  // Entrega compartida con el webhook/reconciliación (idempotente vía reclamo atómico).
  let status: 'delivered' | 'already' | 'error' = 'error'
  let okName: string | null = null
  let service = urlService ?? null
  if (provider === 'sumup' && ref) {
    const r = await fulfillSumUpCheckout(ref)
    service = r.service ?? urlService ?? null
    okName = r.character ?? null
    if (r.ok) status = 'delivered'
    else if (r.paid) status = 'already'
  } else if (session_id) {
    const r = await fulfillCheckoutSession(session_id, urlService)
    service = r.service ?? urlService ?? null
    if (r.ok) {
      status = 'delivered'
      okName = r.character
    } else if (await isSessionPaid(session_id)) {
      // Pago confirmado pero ya reclamado antes (webhook o recarga de la página).
      status = 'already'
    }
  }

  return (
    <PageShell title={service ? t(`${service}.title`) : ''}>
      <div className="box-content">
        <div className="body-box-content centered">
          {status === 'delivered' ? (
            <span className="ok-form-response">{t(`${service}.success`, { name: okName ?? '' })}</span>
          ) : status === 'already' ? (
            <span className="ok-form-response">{t('alreadyProcessed')}</span>
          ) : (
            <span className="red-form-response">{t('error')}</span>
          )}
        </div>
      </div>
    </PageShell>
  )
}
