import { NextRequest, NextResponse } from 'next/server'
import { publicOrigin } from '@/lib/app-url'
import { billingForPurchase, reconcilePurchase } from '@/lib/data/purchases'
import { mockScenario } from '@/lib/integrations/synchron-payments'
import { requirePurchaseOwner } from '@/lib/purchase-api'

/**
 * Ask Synchron for the current payment status and apply it through the
 * verified path (task §6.4, §26). This cannot set `paid` by itself — only a
 * Synchron (or, in dev, mock) report that says so can.
 */
export async function POST(req: NextRequest, ctx: { params: Promise<{ purchaseId: string }> }) {
  const { purchaseId } = await ctx.params
  const guard = await requirePurchaseOwner(purchaseId)
  if (!guard.ok) return guard.response
  const result = await reconcilePurchase({
    bundle: guard.bundle,
    billing: await billingForPurchase(guard.bundle),
    appOrigin: publicOrigin(req),
    scenario: mockScenario(req),
    actorLabel: guard.actorLabel,
  })
  return NextResponse.json({ ok: result.ok, result })
}
