import { NextRequest, NextResponse } from 'next/server'
import { resolveBillingContext } from '@/lib/data/billing-context'
import { requirePermitRequester } from '@/lib/data/permit-request-drafts'
import { logPurchaseEvent } from '@/lib/data/purchase-events'
import { publicOrigin } from '@/lib/app-url'
import {
  getSynchronPayments,
  mockScenario,
  SynchronApiNotConfiguredError,
  SynchronUnavailableError,
} from '@/lib/integrations/synchron-payments'

/**
 * Payment readiness for Buy More Permits step 2 (2026-09-29 task §9.1).
 * Always asks Synchron (or the mock) — nothing cached locally is
 * authoritative. Only safe card fields (brand, last4, expiry) ever leave.
 */
export async function GET(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  const { id: tripId } = await ctx.params
  const access = await requirePermitRequester(tripId)
  if (!access.ok) return access.response
  const { user } = access.guard
  const headers = { 'Cache-Control': 'no-store' }

  const billing = await resolveBillingContext(user, access.trip)
  if (!billing.ok) return NextResponse.json({ error: 'Not authorized to bill for this trip.' }, { status: 403 })

  try {
    const adapter = getSynchronPayments({ scenario: mockScenario(req), appOrigin: publicOrigin(req) })
    const status = await adapter.getCustomerPaymentStatus(billing.billing)
    return NextResponse.json({ ok: true, readiness: status.readiness, cards: status.cards }, { headers })
  } catch (error) {
    if (error instanceof SynchronApiNotConfiguredError || error instanceof SynchronUnavailableError) {
      await logPurchaseEvent({
        event: 'synchron_api_error',
        tripId,
        actorUserId: user.id,
        outcome: 'failed',
        detail: { operation: 'getCustomerPaymentStatus', reason: error.name },
      })
      return NextResponse.json({ ok: true, readiness: 'unavailable', cards: [] }, { headers })
    }
    throw error
  }
}
