/**
 * commerce blueprint · wiring seam for `@platform-modules/billing` IntentStore (floor #6).
 *
 * Adapter-minimalism (CLAUDE.md §4): billing owns the IntentStore CONTRACT + the SQL recipe + TTL;
 * the host owns the durable TABLE (mirrors `DedupStore`). This seam stands up the smallest faithful
 * durable store — an in-memory map keyed by chargeKey — so the composition test can prove the durable
 * charge-intent claim that `0587629` (floor #6) made a required dependency of `settleCharge`. A real
 * host backs `charge_intents` with its own SQL migration and the single-statement atomic claim
 * (`INSERT … ON CONFLICT (charge_key) DO NOTHING RETURNING status`) billing documents on the interface.
 *
 * DURABILITY IS THE POINT (not an optimization to skip): the store persists ACROSS settleCharge calls.
 * A replay of the same chargeKey claims `'settled'` and short-circuits BEFORE the provider is touched —
 * that is the M1 silent-charge-without-record fix, and it is what makes the same-chargeKey replay
 * charge exactly ONCE (see billing's own `index.test.ts` "funnels settled charges once"). So this store
 * is built ONCE per composition (in `beforeEach`, alongside the ledger), never fresh-per-call.
 */
import type { IntentStore } from '@platform-modules/billing'

type IntentRow = {
  status: 'pending' | 'settled'
  amount: number
  currency: string
  providerRef?: string
}

export type CommerceIntentStore = IntentStore & {
  /** Inspect the durable intents (composition assertions / sweep proofs). */
  intents: Map<string, IntentRow>
}

export function createCommerceIntentStore(): CommerceIntentStore {
  const intents = new Map<string, IntentRow>()

  return {
    intents,
    // Single-winner claim over chargeKey (the in-memory analogue of the documented atomic
    // INSERT … ON CONFLICT DO NOTHING RETURNING status): first caller 'won', a settled row
    // short-circuits as 'settled', any other existing row is an in-flight 'pending'.
    async claimIntent(chargeKey, intent) {
      const existing = intents.get(chargeKey)
      if (existing) return existing.status === 'settled' ? 'settled' : 'pending'
      intents.set(chargeKey, { status: 'pending', amount: intent.amount, currency: intent.currency })
      return 'won'
    },
    async recordProviderRef(chargeKey, providerRef) {
      const row = intents.get(chargeKey)
      if (row) row.providerRef = providerRef
    },
    async markIntentSettled(chargeKey) {
      const row = intents.get(chargeKey)
      if (row) row.status = 'settled'
    },
    async listUnsettledIntents(_olderThanMs) {
      return [...intents.entries()]
        .filter(([, v]) => v.status === 'pending')
        .map(([chargeKey, v]) => ({
          chargeKey,
          providerRef: v.providerRef,
          amount: v.amount,
          currency: v.currency,
        }))
    },
  }
}
