/**
 * commerce blueprint · wiring seam for `@platform-modules/billing`.
 *
 * Adapter-minimalism (CLAUDE.md §4): billing's variation axis is the PaymentProvider (stripe/sumit/…).
 * This seam is a single in-memory provider that captures what it was asked to charge/refund, so the
 * composition test can assert the money funnel. A real host imports `@platform-modules/billing/<name>`
 * and registers it via `setProviderFactories`.
 *
 * PATTERN-A (CLAUDE.md §3 — provider-in-charge → config, not a module): invoice-on-charge is a
 * provider SIDE-EFFECT, surfaced as the `emitsInvoiceOnCharge` capability flag + `documentUrls` on the
 * settled result — NOT a `@platform-modules/invoicing` module. This fake sets the flag true (Sumit-
 * like) and returns an invoice URL, demonstrating the flag IS the resolution.
 */
import type {
  ChargeRequest,
  ChargeResult,
  PaymentProvider,
  RefundRequest,
  RefundResult,
} from '@platform-modules/billing'

export type CaptureProvider = {
  provider: PaymentProvider
  charges: ChargeRequest[]
  refunds: RefundRequest[]
}

export function createCaptureProvider(): CaptureProvider {
  const charges: ChargeRequest[] = []
  const refunds: RefundRequest[] = []
  const chargeCurrencies = new Map<string, string>()

  const provider: PaymentProvider = {
    provider: 'fake-sumit',
    emitsInvoiceOnCharge: true, // Pattern-A: invoice is a charge side-effect → config, not a module
    async charge(req: ChargeRequest): Promise<ChargeResult> {
      charges.push(req)
      chargeCurrencies.set(req.chargeKey, req.currency)
      return {
        kind: 'settled',
        chargeKey: req.chargeKey,
        providerRef: `ref-${req.chargeKey}`,
        amount: req.amount,
        currency: req.currency,
        documentUrls: [`https://invoice.test/${req.chargeKey}.pdf`], // the provider-emitted invoice
      }
    },
    async refund(req: RefundRequest): Promise<RefundResult> {
      refunds.push(req)
      const currency = chargeCurrencies.get(req.chargeKey)
      if (!currency) {
        throw new Error(`refund currency missing for charge ${req.chargeKey}`)
      }
      return {
        kind: 'refunded',
        refundKey: req.refundKey,
        chargeKey: req.chargeKey,
        providerRef: `rref-${req.refundKey}`,
        amount: req.amount,
        currency,
      }
    },
    async parseWebhook(): Promise<never> {
      throw new Error('parseWebhook is outside the commerce blueprint flow (webhook ingest is billing-owned)')
    },
  }

  return { provider, charges, refunds }
}
