import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { publicOrigin } from '@/lib/app-url'
import { applyVerifiedPaymentEvent, billingForPurchase, loadPurchaseByReference } from '@/lib/data/purchases'
import { getSynchronPayments, isMockPaymentsActive, mockChooseCheckoutOutcome, mockScenario } from '@/lib/integrations/synchron-payments'

const schema = z.object({
  purchase_reference: z.string().regex(/^hhp_[A-Z2-7]{20}$/),
  outcome: z.enum(['paid', 'failed', 'cancelled', 'pending']),
})

/**
 * Dev-only: the tester's choice on the mock checkout page. Plays the role of
 * Synchron's callback — the report still goes through the single verified
 * path, which refuses `mock` unless mock mode is active.
 */
export async function POST(req: NextRequest) {
  if (process.env.NODE_ENV !== 'development' || !isMockPaymentsActive()) return NextResponse.json({ error: 'Not found' }, { status: 404 })
  const parsed = schema.safeParse(await req.json().catch(() => null))
  if (!parsed.success) return NextResponse.json({ error: 'Invalid request.' }, { status: 400 })
  const { purchase_reference: ref, outcome } = parsed.data

  mockChooseCheckoutOutcome(ref, outcome)
  if (outcome === 'cancelled' || outcome === 'pending') return NextResponse.json({ ok: true, result: { recorded: outcome } })

  const bundle = await loadPurchaseByReference(ref)
  if (!bundle) return NextResponse.json({ error: 'Purchase not found.' }, { status: 404 })
  const adapter = getSynchronPayments({ appOrigin: publicOrigin(req), scenario: mockScenario(req) })
  const report = await adapter.getRoutePurchaseStatus(ref, await billingForPurchase(bundle))
  const result = await applyVerifiedPaymentEvent({ source: 'mock', report, via: 'callback' })
  return NextResponse.json({ ok: true, result })
}
