{
  "openapi": "3.0.3",
  "info": {
    "title": "PA Payments API",
    "version": "1.0.0",
    "description": "Public payments API of the PA Core payment aggregation platform.\n\nThe API exposes the PA model only (payments, refunds, payment instruments, payouts, merchant onboarding, audit trail, webhook delivery log, tenant key lifecycle). PSP/connector concepts never cross this boundary.\n\nConventions:\n- Authentication: `Authorization: Bearer <tenant_api_key>` for every `/v1` route (see `securitySchemes.bearerAuth`). Health probes and the docs portal are unauthenticated.\n- Money: integer minor units (cents) + ISO 4217 alpha-3 currency.\n- Identifiers: type-safe prefixed UUIDs (`pay_…`, `mer_…`, `pin_…`, `pout_…`, `tn_…`, `key_…`).\n- Idempotency: mutating requests take an `Idempotency-Key` header; a retry with the same key and body replays the stored result (`Idempotent-Replayed: true`), a reused key with a different body is rejected with `422 idempotency_key_reuse`.\n- Errors: RFC 7807 `application/problem+json` with stable PA `code` values; PSP error codes are never exposed.\n- Rate limiting: every authenticated request consumes a sliding-window slot (default 100 rpm per tenant+endpoint); over-limit returns `429 rate_limited` with `Retry-After`.\n- Interactive reference: `GET /docs` (branded Redocly reference page) served by the same API instance; `GET /docs/swagger-ui` is the try-it-out console (Swagger UI); this document is `GET /docs/openapi.json`.\n- Guides: the same `/docs` reference page renders the integration guides INSIDE the sidebar «Guides» group — Handover Package, Integration models, SDK README, SDK + Webhooks (Secure Fields), Secure Fields (EN), Field Reference, Payouts Guide, Onboarding Checklist, Термінологія (glossary) — plus the standalone reference sections **Errors**, **Webhooks** and **Sandbox**; `/docs` is the single documentation entry point, the raw markdown surface stays at `GET /portal/docs/{doc}`.\n\nGetting started (10 minutes, sandbox):\n\n1. **Get your keys** — the PA operator hands over the integration package: the tenant API key (`Authorization: Bearer`, shown exactly once), your merchant id, the webhook secret (shown exactly once at webhook registration) and the Secure Fields `captureUrl`. The package contents are listed in the Handover Package guide.\n2. **Create the first payment** — mount the Secure Fields SDK in the deposit page (iframe capture → single-use `vault_token`), register the instrument (`POST /v1/payment-instruments`), create the payment (`POST /v1/payments` with an `Idempotency-Key`); for hosted-page PSPs use `payment_method.type = redirect` and follow `next_action.redirect_url`. Sandbox base URL: `https://sandbox.playpulse.tech`.\n3. **Stand up the webhook receiver** — verify `PA-Webhook-Signature` (`v1=` + HMAC-SHA256 over the raw body), dedup by `PA-Event-Id`, answer `2xx` fast (the **Webhooks** reference has the full contract and a receiver example).\n4. **Walk the onboarding checklist** — the Onboarding Checklist guide details every integration step and the go-live criteria.\n5. **Go live** — request the production base URL `https://payments.playpulse.tech` and production keys from the operator; production keys are issued separately from sandbox keys.\n\nMerchant portal: `https://sandbox.playpulse.tech/portal` (sandbox) · `https://payments.playpulse.tech/portal` (production) — dashboard statistics, payments list, CSV report, webhook delivery health and self-service rotations.\n\nRU documentation of the contract lives in the repository under `docs/api/` (Russian); this spec is the EN-facing reference for external merchants.",
    "x-logo": {
      "url": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgdmlld0JveD0iMCAwIDMyIDMyIiByb2xlPSJpbWciIGFyaWEtbGFiZWw9IlBBIGxvZ28iPgogIDxyZWN0IHg9IjEiIHk9IjEiIHdpZHRoPSIzMCIgaGVpZ2h0PSIzMCIgcng9IjciIGZpbGw9IiMxZDI0MzgiLz4KICA8cmVjdCB4PSIxIiB5PSIxIiB3aWR0aD0iMzAiIGhlaWdodD0iMzAiIHJ4PSI3IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzRCRkYiIHN0cm9rZS13aWR0aD0iMiIvPgogIDx0ZXh0IHg9IjE2IiB5PSIyMS41IiBmb250LWZhbWlseT0iQXJpYWwsIEhlbHZldGljYSwgc2Fucy1zZXJpZiIgZm9udC1zaXplPSIxMyIgZm9udC13ZWlnaHQ9IjcwMCIgZmlsbD0iI2ZmZmZmZiIgdGV4dC1hbmNob3I9Im1pZGRsZSIgbGV0dGVyLXNwYWNpbmc9IjAuNSI+UEE8L3RleHQ+CiAgPGNpcmNsZSBjeD0iMjUuNSIgY3k9IjI1LjUiIHI9IjIuNSIgZmlsbD0iIzMzNEJGRiIvPgo8L3N2Zz4=",
      "altText": "PA Payments API",
      "backgroundColor": "#f5f6f9"
    }
  },
  "servers": [
    {
      "url": "https://payments.playpulse.tech",
      "description": "Production (PlayPulse platform; PA-64 — default)"
    },
    {
      "url": "https://sandbox.playpulse.tech",
      "description": "Sandbox (isolated sandbox environment, PA-79 — dedicated pa-api instance and database; legacy alias: https://167-233-117-108.sslip.io)"
    }
  ],
  "tags": [
    {
      "name": "Payments",
      "description": "Payment lifecycle (create, read). Status machine: PENDING → AUTHORIZED → CAPTURED → PARTIALLY_REFUNDED → REFUNDED; FAILED; UNKNOWN_PENDING_SYNC.\n\n## Transaction statuses\n\nPayment resource states (`GET /v1/payments/{id}`, webhook payloads):\n\n| Status | Meaning | Webhook |\n|---|---|---|\n| `PENDING` | No confirmed authorization yet; attempts/cascade in progress | not delivered |\n| `AUTHORIZED` | An attempt is authorized (funds held or captured per PSP policy) | `payment.authorized` |\n| `CAPTURED` | Capture confirmed (when authorization and capture are separate) | `payment.captured` |\n| `PARTIALLY_REFUNDED` | Confirmed refunds do not cover the full amount | `payment.refunded` |\n| `REFUNDED` | Full amount refunded | `payment.refunded` |\n| `FAILED` | Every attempt/cascade step exhausted without an authorization | `payment.failed` |\n| `UNKNOWN_PENDING_SYNC` | An attempt has no result and sync is in progress; the payment is NOT failed | not delivered — escalates to reconciliation |\n\nAttempt states (inside `attempts_summary[]`): `PENDING` (request in flight), `AUTHORIZED`, `DECLINED_SOFT` (retryable decline — same-route retry, then cascade), `DECLINED_HARD` (final for the attempt — the cascade may continue unless the decline class is terminal), `UNKNOWN` (no result — sync first, cascade blocked until resolved), `FAILED_TECHNICAL` (platform/infrastructure error without proof of execution).\n\nThe decline class behind a `DECLINED_*` attempt decides the cascade behavior — the full taxonomy is in the **Errors** reference. While any attempt is `UNKNOWN`, no new authorization is started on any route (anti-double-charge invariant); the payment stays `UNKNOWN_PENDING_SYNC` until sync resolves it."
    },
    {
      "name": "Payment Instruments",
      "description": "Card instrument registration from single-use vault tokens (Secure Fields capture surface). No PAN/CVV ever reaches the backend API."
    },
    {
      "name": "SDK Capture",
      "description": "Browser card-capture surface of the Secure Fields SDK (PA-48). The sandboxed SDK iframe posts PAN/CVV DIRECTLY here and receives a single-use `vault_token`; PA forwards the card bundle to the capture client and holds the values only in flight — nothing card-shaped is logged or stored. This endpoint is called by the SDK iframe, never by the merchant backend (the backend works with the returned `vault_token` only). See the **SDK + Webhooks** guide for the full capture flow."
    },
    {
      "name": "Refunds",
      "description": "Idempotent refunds of authorized/captured payments."
    },
    {
      "name": "Merchant Payouts",
      "description": "Merchant-facing payouts (PA-83): the casino creates payouts for its own players, reads their statuses and cancels a request before the operator decision. Every payout enters the platform approval gate — a fresh payout is `AWAITING_APPROVAL` and waits for the operator approve/decline; the PSP execution (dispatch to the payment provider) is the operator-side Phase 2. The surface is gated fail-closed: the per-merchant `payouts_enabled` toggle (admin `PUT /v1/merchants/{id}/payouts-enabled`) or the tenant-level payouts flag must be on, otherwise `422 payouts_not_enabled`. PA-107: the OPERATOR may additionally grant the merchant the self-approval waiver (`merchants.payout_self_approval`, admin `PUT /v1/merchants/{id}/payout-self-approval`) — while it is ON the merchant confirms its own `AWAITING_APPROVAL` payouts (approve/decline, `merchant`-role decisions, audited `merchant.payout_approved` / `merchant.payout_declined`); while it is OFF the surface answers `422 payout_self_approval_not_enabled` and the four-eyes discipline stands."
    },
    {
      "name": "Merchant Portal",
      "description": "Self-service surface of the casino merchant portal (PA-65 + PA-66): dashboard statistics, payments list, payment details, CSV report, webhook delivery health, the self-profile read (PA-66: access triple, base URLs, webhook config without the secret) and the webhook URL re-target (PA-66). MVP auth: the same admin Bearer as the operator surfaces (single-principal model) — a merchant-scoped portal key is the production follow-up.\n\nMerchant portal URLs: sandbox `https://sandbox.playpulse.tech/portal` · production `https://payments.playpulse.tech/portal` — the console authenticates with the same Bearer key as the API (single-principal model) and serves the dashboard statistics, payments list, CSV report, webhook delivery health and self-service rotations."
    },
    {
      "name": "Merchant Onboarding",
      "description": "Admin surface: merchants, providers (MIDs), route targets, webhook registration."
    },
    {
      "name": "Webhooks",
      "description": "Signed payment events delivered by the outbox worker + delivery log.\n\n## Event envelope\n\nPA delivers one signed event per terminal payment transition. Event types: `payment.authorized`, `payment.captured`, `payment.refunded`, `payment.failed` — intermediate states (`PENDING`, `UNKNOWN_PENDING_SYNC`) are never delivered.\n\n`POST <webhook_url>` with `Content-Type: application/json` — full `payment.authorized` example:\n\n```json\n{\n \"event_id\": \"0197f6a2-7f8c-7a10-b3ce-2c1a4e5d6f70\",\n \"event_type\": \"payment.authorized\",\n \"created_at\": \"2026-09-28T10:05:00Z\",\n \"data\": {\n  \"payment_id\": \"pay_01a0ec3b7f8c4d5e9a1b2c3d\",\n  \"merchant_id\": \"mer_01a0ec3a1b2c4d5e9a1b2c3d\",\n  \"status\": \"AUTHORIZED\",\n  \"amount\": 1050,\n  \"currency\": \"EUR\",\n  \"instrument_id\": \"pin_01a0ec3b1a2b4c5d9a1b2c3d\",\n  \"correlation_id\": \"7c1e4a8f0b3d4e5f9a0b1c2d\",\n  \"attempts_summary\": [\n   {\n    \"seq\": 1,\n    \"route_target\": {\n     \"provider\": \"apcopay\",\n     \"mid\": \"mid-main\"\n    },\n    \"status\": \"AUTHORIZED\"\n   }\n  ]\n }\n}\n```\n\n`event_id` is a UUIDv7 minted once per state transition; `data.attempts_summary` is the collapsed attempt journal — the same structure the payment resource carries. `data` carries no PSP secrets and no card data: the instrument appears by its `pin_…` id only.\n\n## Delivery headers\n\nEvery delivery — first attempt and every retry — carries:\n\n| Header | Value |\n|---|---|\n| `PA-Event-Id` | The payload `event_id` — the receiver dedup key |\n| `PA-Webhook-Signature` | `v1=<hex(HMAC-SHA256(raw_body, webhook_secret))>` — lowercase hex over the RAW body bytes |\n| `Content-Type` | `application/json` |\n\nGiven the webhook secret `whs_5f3a9c1e7b2d4068ae13d5f70c8b9e42` and the exact body above, the signature header is:\n\n```\nPA-Webhook-Signature: v1=0c4377f83b4194131e88c0d61ca00ef7f7727a52b0cf03a079adf849045c0b5d\n```\n\nAny byte difference (whitespace, key order, re-serialization) produces a different signature — verify the RAW bytes.\n\n## Signature verification (pseudocode)\n\nVerify before parsing JSON, over the raw request body:\n\n```\nexpected = \"v1=\" + lowercase_hex(HMAC_SHA256(key = webhook_secret, message = raw_body))\nprovided = header \"PA-Webhook-Signature\"\nok = constant_time_equals(expected, provided)\nif not ok:\n respond 401 and do not process the event\n```\n\nReference receiver (Node/Express):\n\n```js\nconst crypto = require('crypto');\nconst seen = new Set(); // production: a durable store (DB/Redis), not memory\n\napp.post('/pa/webhook',\n express.raw({ type: '*/*' }), // RAW body — required for the signature\n (req, res) => {\n  const sig = String(req.get('PA-Webhook-Signature') || '');\n  const expected = 'v1=' + crypto.createHmac('sha256', process.env.PA_WEBHOOK_SECRET)\n   .update(req.body).digest('hex');\n  const ok = sig.length === expected.length &&\n   crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));\n  if (!ok) return res.sendStatus(401); // wrong signature\n\n  const eventId = req.get('PA-Event-Id'); // at-least-once delivery\n  if (seen.has(eventId)) return res.sendStatus(200);\n  seen.add(eventId);\n\n  const ev = JSON.parse(req.body);\n  switch (ev.event_type) {\n   case 'payment.authorized':\n   case 'payment.captured': creditPlayer(ev.data); break; // credit the deposit\n   case 'payment.refunded': debitPlayer(ev.data); break;\n   case 'payment.failed': markFailed(ev.data); break;\n  }\n  res.sendStatus(200); // 2xx = delivered, otherwise a retry is scheduled\n });\n```\n\n## Delivery guarantees\n\n- **At-least-once + dedup.** The event is enqueued into the delivery outbox in the SAME database transaction as the payment status change — either both persist or neither. Every retry redelivers the exact same payload bytes: the signature and `PA-Event-Id` are stable across attempts; dedup by `PA-Event-Id`.\n- **One event per transition.** An event is unique per payment + event type + announced status: the receiver sees every terminal fact exactly once, and different transitions of one payment (`AUTHORIZED` → `PARTIALLY_REFUNDED` → `REFUNDED`) carry their own events.\n- **Retry ladder.** A non-2xx answer or a timeout is retried after 60 s, 300 s, 1800 s and 7200 s — a budget of 5 attempts per event; after that the delivery is marked `DEAD` (dead-letter — the payment itself is unaffected). Answer `2xx` quickly: the delivery timeout is 5 s by default.\n- **Delivery status ≠ payment status.** `DELIVERED` (receiver answered `2xx`), `PENDING` (in the retry ladder), `DEAD` (budget exhausted) describe the notification only — money operations keep working. Delivery log (merchant-scoped): `GET /v1/merchants/{id}/webhooks/deliveries` with `?payment_id=…` per transaction, or the portal Integration tab.\n\n## Webhook secret rotation\n\n`POST /v1/merchants/{id}/rotate-webhook-secret` re-keys deliveries without downtime:\n\n- the new secret (`whs_…`) is shown exactly once and becomes active immediately — every delivery after the rotation is signed with the NEW secret;\n- the replaced secret stays valid until `rotated_at + grace` (default 7 days; the answer carries `old_secret_expires_at`) — during the grace window verify BOTH secrets (dual-verify), after it reject the old one;\n- rollout: deploy dual-verify → rotate → confirm old-secret verifications stop arriving.\n\nDual-verify pseudocode:\n\n```\nok = constant_time_equals(sig, sign(active_secret, raw_body))\nif not ok and now < old_secret_expires_at:\n ok = constant_time_equals(sig, sign(previous_secret, raw_body))\n```\n\nRegistration: the operator registers the endpoint (`POST /v1/merchants/{id}/webhook`) and hands over the `whs_…` secret once; the merchant re-targets the URL itself via `PATCH /v1/merchants/{id}/webhook-url` (HTTPS-only; a URL change does NOT rotate the secret).",
      "x-displayName": "Webhooks"
    },
    {
      "name": "Errors",
      "x-displayName": "Errors",
      "description": "Error model of the PA API: RFC 7807 problem responses, the card-decline taxonomy and the stable error codes of every merchant-facing endpoint group.\n\n## Error format\n\nEvery error answer is RFC 7807 `application/problem+json`:\n\n```json\n{\n \"type\": \"about:blank\",\n \"title\": \"Unprocessable Entity\",\n \"status\": 422,\n \"code\": \"no_eligible_route\",\n \"message\": \"no eligible route target for this payment\",\n \"payment_id\": \"pay_01a0ec3b7f8c4d5e9a1b2c3d\"\n}\n```\n\n| Field | Meaning |\n|---|---|\n| `type` | RFC 7807 type URI; the stable `code` field is the discriminator |\n| `title` | HTTP status phrase |\n| `status` | HTTP status code |\n| `code` | Stable PA error code — switch on this value, never on `message` |\n| `message` | Human-readable explanation; never echoes card data |\n| `payment_id` | Payment reference, when the error is bound to one |\n\nCodes are stable PA values: PSP/processor error codes never cross the API boundary.\n\n## Card declines are not HTTP errors\n\nA declined card is a payment outcome, not an HTTP error: `POST /v1/payments` answers `201` (the payment resource exists) and `GET /v1/payments/{id}` answers `200` — the money outcome travels inside the payment resource:\n\n- `status` = `FAILED` once every attempt and cascade step is exhausted without an authorization;\n- `attempts_summary[]` carries one entry per attempt — `seq`, `route_target` (provider + MID) and the attempt `status` (`DECLINED_SOFT`, `DECLINED_HARD`, `UNKNOWN`, `FAILED_TECHNICAL` or `AUTHORIZED`);\n- the terminal `payment.failed` webhook announces the same outcome (see **Webhooks**).\n\n## Decline classes\n\nEvery attempt decline is normalized by the platform into exactly one class; the class — never a raw processor code — drives the retry/cascade/stop decision:\n\n| Decline class | Meaning | Platform behavior | Merchant action |\n|---|---|---|---|\n| `SOFT_RETRYABLE` | Retryable decline (insufficient funds, 3DS timeout) | Retry on the same route target, then cascade to the next route target | **retry-safe** — the same card often succeeds on a later retry |\n| `HARD_CASCADE_ALLOWED` | Final for this attempt; another route may still succeed | Cascade continues on the next route target | **final** for this attempt — retrying with another card/instrument is possible |\n| `HARD_TERMINAL` | Pointless to continue (stolen card, fraud block, invalid instrument) | The payment stops as `FAILED`; the cascade does not continue | **final** — contact support if the outcome is unexpected |\n| `UNKNOWN` | No result: timeout, connection drop, unparsable answer | Sync first — the cascade is blocked until the outcome is resolved | **retry-safe** — wait; the payment stays `PENDING`/`UNKNOWN_PENDING_SYNC` while syncing |\n| `TECHNICAL` | Platform/infrastructure error without proof of execution | Retry of the same attempt, or cascade by policy | **retry-safe** |\n\nUnknown processor codes default to `UNKNOWN` — the safe side: sync before anything else.\n\n## Problem codes\n\nDecline Type over the API error codes: **soft** — the same call may succeed later (retry-safe); **hard** — the call as submitted is final, something must be fixed first; **technical** — platform-side, retry-safe.\n\n### Payments\n\n`POST /v1/payments`, `GET /v1/payments/{id}`:\n\n| Code | HTTP | Decline Type | Merchant action |\n|---|---|---|---|\n| `invalid_request` | 400 / 422 | hard | final — fix the request; a corrected retry is safe |\n| `unsupported_media_type` | 415 | hard | final — send `Content-Type: application/json` |\n| `unknown_merchant` | 404 / 422 | hard | final — `merchant_id` is not in this tenant |\n| `unsupported_payment_method` | 422 | hard | final — use `card` (instrument) or `redirect` |\n| `unknown_instrument` | 422 | hard | final — register the instrument first |\n| `card_expired` | 422 | hard | final for the card — capture a new one |\n| `invalid_card_number` / `invalid_card_expiry` / `invalid_card_cvc` / `invalid_card_holder` | 422 | hard | final — raw-card (H2H) surface validation |\n| `h2h_not_enabled` | 422 | hard | contact support — the raw-card gate is closed for this merchant |\n| `no_eligible_route` | 422 | hard | contact support — no eligible route target (routing configuration) |\n| `no_eligible_redirect_route` | 422 | hard | contact support — no redirect-capable route for `type: redirect` |\n| `idempotency_in_flight` | 409 | soft | retry-safe — wait `Retry-After`, then `GET` the payment |\n| `idempotency_key_reuse` | 422 | hard | final — a key is replayable only with the same body; new payment = new key |\n| `payment_not_found` | 404 | hard | final — a foreign-tenant payment is a plain 404 |\n| `rate_limited` | 429 | soft | retry-safe — honor `Retry-After` |\n| `internal` | 500 | technical | retry-safe — transient; contact support if it persists |\n\n### Refunds\n\n`POST /v1/refunds`:\n\n| Code | HTTP | Decline Type | Merchant action |\n|---|---|---|---|\n| `invalid_request` | 400 / 422 | hard | final — fix the request |\n| `refund_exceeds_amount` | 422 | hard | final — refunds may not exceed the remaining amount; partial refunds sum up |\n| `invalid_state` | 422 | hard | final — check the payment status first (refundable states only) |\n| `payment_not_found` | 404 | hard | final |\n| `idempotency_in_flight` | 409 | soft | retry-safe — wait `Retry-After` |\n| `idempotency_key_reuse` | 422 | hard | final — new refund = new key |\n| `rate_limited` | 429 | soft | retry-safe |\n| `internal` | 500 | technical | retry-safe |\n\n### Payment instruments\n\n`POST /v1/payment-instruments`, `GET /v1/payment-instruments/{id}`:\n\n| Code | HTTP | Decline Type | Merchant action |\n|---|---|---|---|\n| `invalid_request` | 400 / 422 | hard | final — fix the request |\n| `unknown_merchant` | 422 | hard | final — `merchant_id` is not in this tenant |\n| `vault_token_unknown` | 422 | hard | final — the vault token was not minted; re-run the Secure Fields capture |\n| `vault_token_already_registered` | 409 | hard | final — single use: this token is already an instrument |\n| `idempotency_in_flight` | 409 | soft | retry-safe — wait `Retry-After` |\n| `idempotency_key_reuse` | 422 | hard | final |\n| `vault_unavailable` | 502 | technical | retry-safe — vault-side outage |\n| `rate_limited` | 429 | soft | retry-safe |\n| `internal` | 500 | technical | retry-safe |\n\n### Secure Fields capture\n\n`POST /v1/sdk/capture` (browser contour — publishable key):\n\n| Code | HTTP | Decline Type | Merchant action |\n|---|---|---|---|\n| `invalid_publishable_key` | 401 | hard | final — publishable key missing/unknown |\n| `origin_not_allowed` | 403 | hard | final — request origin not on the configured allowlist |\n| `invalid_request` | 400 / 422 | hard | final — fix the card payload |\n| `capture_rejected` | 422 | hard | final — the capture surface rejected the card |\n| `rate_limited` | 429 | soft | retry-safe — per-key/per-IP capture quota |\n| `capture_unavailable` | 502 | technical | retry-safe — capture surface unreachable |\n\n### Merchant payouts\n\n`POST /v1/merchants/{id}/payouts`, `GET /v1/merchants/{id}/payouts/{payout_id}`, `POST /v1/merchants/{id}/payouts/{payout_id}/cancel`, `POST /v1/merchants/{id}/payouts/{payout_id}/approve`, `POST /v1/merchants/{id}/payouts/{payout_id}/decline`:\n\n| Code | HTTP | Decline Type | Merchant action |\n|---|---|---|---|\n| `invalid_request` | 400 / 422 | hard | final — fix the request (no PAN/CVV anywhere in the payload) |\n| `payouts_not_enabled` | 422 | hard | contact support — the payouts gate is off for this merchant |\n| `unknown_instrument` | 422 | hard | final — the source instrument is unknown or belongs to another merchant |\n| `instrument_not_payout_eligible` | 422 | hard | final — the instrument is not usable as a payout receiver (status `DEACTIVATED`; the receiver accepts `ACTIVE` or `USED`) |\n| `limit_exceeded` | 422 | hard | contact support — payout limit exceeded |\n| `payout_not_found` | 404 | hard | final |\n| `idempotency_in_flight` | 409 | soft | retry-safe — wait `Retry-After` |\n| `idempotency_key_reuse` | 422 | hard | final |\n| `payout_not_cancellable` | 409 | hard | final — the payout is outside the merchant-cancellable range (e.g. already approved) |\n| `payout_already_final` | 409 | hard | final — the payout is not awaiting approval (self-approval may only decide an `AWAITING_APPROVAL` payout) |\n| `payout_self_approval_not_enabled` | 422 | hard | contact support — the merchant self-approval flag is off; the operator decides the payout |\n| `invalid_state_transition` | 409 | hard | final — approval-gate state matrix violation |\n| `rate_limited` | 429 | soft | retry-safe |\n| `internal` | 500 | technical | retry-safe |\n\n`429 rate_limited` applies to every endpoint (sliding window per key + endpoint) and always carries `Retry-After`.\n\n### Merchant portal — PSP enablement\n\n`GET /v1/merchants/{id}/providers`, `PUT /v1/merchants/{id}/providers/{code}`:\n\n| Code | HTTP | Decline Type | Merchant action |\n|---|---|---|---|\n| `merchant_not_found` | 404 | hard | final — a foreign/unknown merchant (or an unconfigured provider code) is a plain 404 |\n| `provider_locked_by_operator` | 403 | hard | final — the operator disabled this PSP for the merchant; the merchant cannot re-enable it, contact support |\n| `operator_locked_is_operator_only` | 422 | hard | final — remove the operator-only `operator_locked` field from the request: the merchant cannot set or clear the operator lock |\n| `rate_limited` | 429 | soft | retry-safe — honor `Retry-After` |\n| `internal` | 500 | technical | retry-safe — transient; contact support if it persists |\n"
    },
    {
      "name": "Sandbox",
      "x-displayName": "Sandbox",
      "description": "Sandbox and production environments: base URLs, mock-vault behavior, test cards and how to get keys.\n\n## Environments\n\n| Environment | Base URL | Notes |\n|---|---|---|\n| Production | `https://payments.playpulse.tech` | Live processing; production keys are issued separately from sandbox keys |\n| Sandbox | `https://sandbox.playpulse.tech` | Isolated instance (own process + own database); the mock engine authorizes every well-formed payment locally |\n\nBoth environments serve the same API surface: `/docs` (this reference), `/docs/swagger-ui` (try-it-out console), `/docs/openapi.json` (machine-readable spec), `/portal` (merchant portal), plus the unauthenticated health probes `GET /healthz` and `GET /ready`.\n\n## Sandbox behavior\n\n- The sandbox runs the mock execution engine: every well-formed payment reaches a terminal status locally (no PSP round-trip), so the whole flow — instruments, payments, refunds, webhooks, delivery log — is exercisable end-to-end.\n- The sandbox does not impose amount limits (the mock engine authorizes any well-formed amount); rate limits apply as in production (sliding window per key + endpoint, default 100 requests/min, over-limit → `429 rate_limited` with `Retry-After`).\n- The webhook outbox works for real: register an HTTPS endpoint and the sandbox delivers the same signed events with the same retry ladder (see **Webhooks**).\n- The webhook secret and the tenant API key are environment-specific — sandbox keys never work against production and vice versa.\n\n## Self-describing vault tokens (mock vault)\n\nThe sandbox mock vault accepts self-describing demo tokens `vtok_<brand>_<last4>-<suffix>` — the token names the card it resolves to (`vtok_visa_1111-quickstart` → VISA ending `1111`). Register an instrument with it:\n\n```bash\ncurl -s -X POST \"https://sandbox.playpulse.tech/v1/payment-instruments\" \\\n -H \"Authorization: Bearer $KEY\" -H \"Idempotency-Key: qs-instrument-1\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"merchant_id\":\"mer_...\",\"vault_token\":\"vtok_visa_1111-quickstart\",\"customer_reference\":\"player_1\"}'\n# → {\"instrument_id\":\"pin_...\",\"card_meta\":{\"masked_pan\":\"****1111\",\"brand\":\"VISA\"},\"status\":\"ACTIVE\"}\n```\n\nThe production capture surface (`POST /v1/sdk/capture` behind the Secure Fields SDK) answers with the same single-use vault-token shape — the backend integration does not change between environments.\n\n## Test cards\n\nThe PA sandbox mock vault does not validate card numbers at all — cards exist only as vault tokens. Test card numbers matter when the operator attaches a real PSP sandbox route to your merchant:\n\n| Network | Number | Expiry | CVC | Holder | Expected result |\n|---|---|---|---|---|---|\n| VISA (3DS frictionless) | `4500000000004454` | `12/30` | any | `Frictionless Processed` | Frictionless 3DS → processed → `AUTHORIZED` |\n| VISA (hosted page) | `4111 1111 1111 1111` | `12/30` | `123` | any | Hosted-page flow with partial-complete semantics in the PSP sandbox |\n| Mastercard | `5555 5555 5555 4444` | `12/30` | `123` | any | Alternate network |\n| VISA (3DS challenge) | `4000 0000 0000 0002` | `12/30` | `123` | any | 3DS challenge flow |\n\nThe holder name drives the 3DS scenario: `Frictionless Processed` completes the challenge without user interaction.\n\n## Getting keys\n\nSandbox and production credentials are issued by the PA operator through the handover package (see the **Handover Package** guide): tenant API key (Bearer — shown exactly once), merchant id, webhook secret (`whs_…` — shown exactly once at webhook registration) and the SDK `captureUrl`. Production keys are issued separately — go-live re-runs the handover against the production base URL (see the **Onboarding Checklist** guide)."
    },
    {
      "name": "Secure Fields (EN)",
      "x-displayName": "Secure Fields (EN)",
      "description": "English summary of the Secure Fields integration: the PCI boundary, the publishable key and the browser capture flow. The step-by-step guide is **SDK + Webhooks** (Russian).\n\n## PCI boundary\n\nPAN/CVV exist only inside the PA-hosted iframe:\n\n- the casino deposit page mounts the Secure Fields SDK (`pa-sdk/secure-fields.js` + the iframe page served from the PA origin);\n- the iframe runs sandboxed WITHOUT same-origin access: casino JavaScript has NO DOM access to the field values, and the frame cannot read the parent page;\n- PAN/CVV travel from the iframe DIRECTLY to the PA capture endpoint — the casino backend never sees them, and the backend API request schema has no card fields at all;\n- PA stores only the vault-token reference and masked metadata (brand, last4, expiry) — no PAN prefix, no CVV, nothing in logs or audit.\n\n## Publishable key (pk_…)\n\nThe capture endpoint authenticates the BROWSER with a publishable key — a public, derived identifier bound to the merchant: it is not a secret, it grants no privileges, and it selects the capture rate-limit budget. Every money-moving call keeps using the tenant Bearer key; the publishable key never authenticates a backend.\n\n## Capture flow\n\n1. Mount the SDK: `PASecureFields.mount({container, frameUrl, captureUrl, publishableKey, onToken, onError, onReady})`.\n2. The player types PAN/CVV into the iframe fields; the iframe POSTs them to the capture URL `https://<pa-origin>/v1/sdk/capture` with the `X-Publishable-Key` header and a flat JSON body (`card_number`, `cvc`, `expiry_month`, `expiry_year`, `card_holder_name`) — the only network call that ever carries card data.\n3. The capture answers `201` with a single-use `vault_token` (opaque string), delivered to `onToken` via postMessage.\n4. The casino backend exchanges it: `POST /v1/payment-instruments` with `{merchant_id, vault_token, customer_reference}` → a `pin_…` instrument (single-use, consumed atomically by the first payment).\n5. `POST /v1/payments` with `payment_method: {type: card, instrument_id: \"pin_…\"}` — the cascade runs; the outcome arrives via the signed webhook and/or `GET /v1/payments/{id}`.\n\n## Controls\n\n| Control | Value |\n|---|---|\n| Capture endpoint | `POST /v1/sdk/capture` (CORS preflight `OPTIONS` unauthenticated, `204`) |\n| Browser auth | `X-Publishable-Key` header (`pk_…`, PUBLIC) |\n| Rate limits | per publishable key (default 30/min) + per-IP window; over-limit → `429 rate_limited` |\n| Origin allowlist | optional — when configured, a foreign origin answers `403 origin_not_allowed` |\n| Transport | HTTPS-only on public addresses in production (fail-fast at startup otherwise) |\n\nCapture error codes: `invalid_publishable_key` (401), `origin_not_allowed` (403), `invalid_request` / `capture_rejected` (422), `rate_limited` (429), `capture_unavailable` (502) — the full table is in **Errors**."
    },
    {
      "name": "Payouts",
      "description": "Payout domain (approval gate, limits, idempotent mutations). The whole surface is gated by the fail-closed `payouts_enabled` feature flag — 404 `feature_disabled` while off."
    },
    {
      "name": "Tenant Keys",
      "description": "Tenant API key lifecycle: rotation with 24h grace, immediate revocation."
    },
    {
      "name": "Audit",
      "description": "Immutable audit trail of configuration changes."
    },
    {
      "name": "Ops",
      "description": "Unauthenticated health probes for orchestrators."
    },
    {
      "name": "Docs",
      "description": "This documentation portal."
    },
    {
      "name": "PSP Portal",
      "description": "Processor-scoped self-service surface (PA-70). The Bearer key IS the connector scope: every route under /v1/psp is filtered by that connector code on the SQL side; a foreign MCA reference is a plain 404 (never 403). see docs/operations/psp-portal.md."
    },
    {
      "name": "PSP Callbacks",
      "description": "Provider-to-PA webhook surface (PA-108): the settlement callbacks payment providers deliver to `POST /v1/psp/{connector}/callback`. NOT part of the merchant API — the caller is the PSP, the request authenticates by the connector contract itself (the Apcopay `Signature` HMAC; the BTQ Finance postback is an unauthenticated trigger whose fact comes from the authenticated sync re-ask). The receiver is fail-closed: a callback naming no PA attempt is acknowledged `200` (no endless PSP retries) and logged; the projection follows the ADR-0002 state machine; redeliveries of the same `(connector, external id, status)` event are acknowledged without changes. Full contract: repository `docs/operations/psp-webhooks.md`."
    },
    {
      "name": "PSP Management",
      "description": "PA-135/PA-136: operator-owned PSP definition surface (global catalog, level 1). The catalog is a dictionary WITHOUT credential values (ADR-0008 §3): no read ever returns a secret. Admin-only mutations answer `403 forbidden` to a merchant-scoped key. Every mutation is audited in the same transaction (`psp_catalog.updated`, `credential_field.*`, `terminal_template.*`, `payment_method.*`). Level-2 merchant configuration (connections/terminals/routing) is documented under Merchant Onboarding."
    }
  ],
  "security": [
    {
      "bearerAuth": []
    }
  ],
  "paths": {
    "/healthz": {
      "get": {
        "tags": [
          "Ops"
        ],
        "summary": "Liveness probe",
        "description": "Returns `200` while the server process is alive. Deliberately performs NO database check: restarting the process cannot heal PostgreSQL, so liveness stays independent of it. Unauthenticated.",
        "security": [],
        "operationId": "healthz",
        "responses": {
          "200": {
            "description": "Process is alive",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthStatus"
                }
              }
            }
          }
        }
      }
    },
    "/ready": {
      "get": {
        "tags": [
          "Ops"
        ],
        "summary": "Readiness probe",
        "description": "Returns `200` while PostgreSQL answers a probe query (`SELECT 1`, 3s timeout), `503` when it does not. The orchestrator removes an unready instance from traffic rotation WITHOUT restarting it; readiness self-heals when the database recovers. Unauthenticated.",
        "security": [],
        "operationId": "ready",
        "responses": {
          "200": {
            "description": "Database is reachable",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReadinessStatus"
                }
              }
            }
          },
          "503": {
            "description": "Database is unreachable",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReadinessStatus"
                }
              }
            }
          }
        }
      }
    },
    "/docs": {
      "get": {
        "tags": [
          "Docs"
        ],
        "summary": "API reference (branded Redocly page)",
        "description": "Serves the branded, self-contained Redocly reference page (PA-73) built from this document. Unauthenticated; safe to bookmark for integration engineers.",
        "security": [],
        "operationId": "getDocs",
        "responses": {
          "200": {
            "description": "Redocly reference HTML page",
            "content": {
              "text/html": {
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    },
    "/docs/openapi.json": {
      "get": {
        "tags": [
          "Docs"
        ],
        "summary": "OpenAPI 3.0 document of this API",
        "description": "The versioned machine-readable contract (same bytes as the repository file `docs/api/openapi.json`). Unauthenticated.",
        "security": [],
        "operationId": "getOpenapiSpec",
        "responses": {
          "200": {
            "description": "OpenAPI 3.0.3 document",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            }
          }
        }
      }
    },
    "/docs/static/{asset}": {
      "get": {
        "tags": [
          "Docs"
        ],
        "summary": "Static asset of the docs portal (vendored Swagger UI)",
        "description": "Serves the vendored swagger-ui-dist assets (`swagger-ui.css`, `swagger-ui-bundle.js`) from a closed allowlist — any other asset name is a plain 404. Unauthenticated.",
        "security": [],
        "operationId": "getDocsStaticAsset",
        "parameters": [
          {
            "name": "asset",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "enum": [
                "swagger-ui.css",
                "swagger-ui-bundle.js"
              ]
            },
            "description": "Vendored asset file name."
          }
        ],
        "responses": {
          "200": {
            "description": "Asset content (CSS or JavaScript)",
            "content": {
              "text/css": {
                "schema": {
                  "type": "string"
                }
              },
              "application/javascript": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "Unknown asset name (closed allowlist)"
          }
        }
      }
    },
    "/favicon.ico": {
      "get": {
        "tags": [
          "Ops"
        ],
        "summary": "Favicon probe (PA-111)",
        "description": "Answers the browser tab-icon probe on this origin with a constant body-less `204 No Content`. Unauthenticated by design: the tab-icon request is browser chrome (it can never carry the admin Bearer), the response leaks nothing and keeps the spurious 404 out of the operator console log.",
        "security": [],
        "operationId": "favicon204",
        "responses": {
          "204": {
            "description": "No content (the origin ships no favicon)"
          }
        }
      }
    },
    "/admin": {
      "get": {
        "tags": [
          "Admin"
        ],
        "summary": "Admin console (PA-52, PA-97, PA-136)",
        "description": "Serves the operator console of the tenant — a same-origin JavaScript application over the authenticated `/v1` admin API (PA-136: merchants registry and merchant card, PSP catalog with the six Configure tabs, payment routing and routing preview, payouts queue, monitoring and the audit log). The served document is the console SHELL: it carries no page content and references exactly two content-hashed same-origin bundles, `/admin/static/admin.css?v=<hash>` and `/admin/static/admin.js?v=<hash>` — no third asset, no CDN, no inline handler. Every response is `Cache-Control: no-store` with the strict same-origin CSP (`script-src 'self'; connect-src 'self'; frame-ancestors 'none'`) plus `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY` and `Referrer-Policy: no-referrer`.\n\nBearer-authenticated since PA-97 (the same extractor/authorizer as the admin API routes): the tenant (admin) key answers 200, a merchant-scoped key answers 403 forbidden, a missing or unknown key answers 401 (an HTML navigation — `Accept: text/html` — receives the minimal login shell instead of the RFC 7807 problem; a non-browser client gets the problem body). Every API call from the console carries the admin Bearer to the authenticated `/v1/...` routes itself. Operator surface — see `docs/operations/admin-ui.md`.",
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "operationId": "getAdminConsole",
        "responses": {
          "200": {
            "description": "Admin console HTML page",
            "content": {
              "text/html": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "description": "Missing or unknown tenant key",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin required)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/admin/static/{asset}": {
      "get": {
        "tags": [
          "Admin"
        ],
        "summary": "Admin console bundles (PA-52, PA-97, PA-136)",
        "description": "Serves the two console bundles the `/admin` shell references: `admin.css` (the PA-136 design system — tokens, shell, components, pages, breakpoints) and `admin.js` (the runtime modules plus the page modules), each built by concatenating the checked-in sources and requested with a `?v=<content-hash>` cache buster. The allowlist is closed — `admin.css`, `admin.js`, anything else is a plain 404 AFTER the auth gate (no path traversal surface, no directory listing). Bearer-authenticated since PA-97, the same gate as the console page (tenant key 200, merchant key 403, no key 401). Every asset answer carries `Cache-Control: no-store`: the page and its bundles are redeployed atomically, so a cached copy could only desynchronize from the fresh page, and an Authorization-gated response must never be stored by a shared cache. `X-Content-Type-Options: nosniff` on both.",
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "operationId": "getAdminConsoleAsset",
        "parameters": [
          {
            "name": "asset",
            "in": "path",
            "required": true,
            "description": "Static asset file name (allowlist: admin.css, admin.js).",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The requested asset (CSS or JavaScript)",
            "content": {
              "text/css": {
                "schema": {
                  "type": "string"
                }
              },
              "application/javascript": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "Unknown asset (closed allowlist)"
          },
          "401": {
            "description": "Missing or unknown tenant key",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin required)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/portal": {
      "get": {
        "tags": [
          "Admin"
        ],
        "summary": "Merchant portal console",
        "description": "PA-65: the self-service merchant portal console at `/portal` — a static, same-origin SPA served by the API itself (the PA-52 `/admin` pattern: embedded at compile time, no filesystem lookup). The surface is UNAUTHENTICATED on the serving side: it carries no tenant data of its own — every API call the SPA makes goes to the authenticated `/v1` routes with the Bearer key typed into the login box (kept in sessionStorage). A strict CSP (same-origin scripts/styles/connect only, no framing) is delivered by the HTML itself plus hardening headers. This surface is NOT part of the API contract; it is pinned by the router manifest.",
        "operationId": "merchantPortalConsole",
        "security": [],
        "responses": {
          "200": {
            "description": "Merchant portal console page",
            "content": {
              "text/html": {
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    },
    "/portal/static/{asset}": {
      "get": {
        "tags": [
          "Admin"
        ],
        "summary": "Merchant portal static assets",
        "description": "PA-65: the static assets of the `/portal` console (portal.css, portal.js). The allowlist is closed — anything else is a plain 404 (no path traversal surface, no directory listing).",
        "operationId": "merchantPortalStaticAsset",
        "security": [],
        "parameters": [
          {
            "name": "asset",
            "in": "path",
            "required": true,
            "description": "Static asset file name of the portal console.",
            "schema": {
              "type": "string",
              "enum": [
                "portal.css",
                "portal.js"
              ]
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Static asset",
            "content": {
              "text/css": {
                "schema": {
                  "type": "string"
                }
              },
              "application/javascript": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "Unknown asset (closed allowlist)"
          }
        }
      }
    },
    "/v1/payments": {
      "post": {
        "tags": [
          "Payments"
        ],
        "summary": "Create a payment",
        "description": "Idempotent payment creation. The request runs the routing cascade (eligible Route Targets by currency/capture method) through the execution engine; the response is the logical payment of the PA model (attempt journal collapsed into `attempts_summary`, no PSP internals).\n\nDeterministic client errors (`unknown_merchant`, `no_eligible_route`, validation failures) are stored with the idempotency record and are replayed identically on retry with the same key.\n\nRequires the `Idempotency-Key` header.",
        "operationId": "createPayment",
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreatePaymentRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Payment created. Idempotent replay: the same `Idempotency-Key` + body returns the ORIGINAL stored result — the same `201` status and body, header `Idempotent-Replayed: true`, no new logical payment (a stored deterministic error problem replays with its original status and problem body).",
            "headers": {
              "Idempotent-Replayed": {
                "description": "`false` on a fresh execution, `true` on a replay of the stored result (present on every response of this idempotent POST).",
                "schema": {
                  "type": "string",
                  "enum": [
                    "true",
                    "false"
                  ]
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaymentResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "description": "Another request with the same idempotency key is still in flight (`idempotency_in_flight`); `Retry-After` carries the claim window",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request`), unknown merchant (`unknown_merchant`), no eligible route target (`no_eligible_route`; for `payment_method.type=redirect` — no `redirect_hpp`-capable route: `no_eligible_redirect_route`), unsupported method (`unsupported_payment_method`) or idempotency key reuse (`idempotency_key_reuse`), H2H gate closed (`h2h_not_enabled`), card validation (`invalid_card_number`, `invalid_card_expiry`, `card_expired`, `invalid_card_holder`, `invalid_card_cvc`), the 3DS option (`invalid_request`: unknown value, non-raw-card form, or `three_ds` without a parseable `session_context.browser.ip_address`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/payments/{id}": {
      "get": {
        "tags": [
          "Payments"
        ],
        "summary": "Fetch a payment",
        "description": "Returns the last confirmed state of the payment with the collapsed attempt journal. Fresh reads never call the PSP; while the state is `PENDING` or `UNKNOWN_PENDING_SYNC` the response carries `next_action` and a `Retry-After` header (synchronization is asynchronous — the source of truth is this GET).",
        "operationId": "getPayment",
        "parameters": [
          {
            "$ref": "#/components/parameters/PaymentId"
          }
        ],
        "responses": {
          "200": {
            "description": "Payment state",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaymentResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Payment not found in this tenant (`payment_not_found`) — a foreign-tenant payment is a plain 404",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/refunds": {
      "post": {
        "tags": [
          "Refunds"
        ],
        "summary": "Create a refund",
        "description": "Idempotent full or partial refund of a payment in `AUTHORIZED` / `CAPTURED` / `PARTIALLY_REFUNDED` / `REFUNDED` state. The refund amount never exceeds the remaining refundable amount; the payment status is recomputed (`PARTIALLY_REFUNDED` → `REFUNDED`). Requires the `Idempotency-Key` header.",
        "operationId": "createRefund",
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateRefundRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Refund created. Idempotent replay: the same `Idempotency-Key` + body returns the ORIGINAL stored result — the same `201` status and body, header `Idempotent-Replayed: true`, no second refund (a stored deterministic error problem replays with its original status and problem body).",
            "headers": {
              "Idempotent-Replayed": {
                "description": "`false` on a fresh execution, `true` on a replay of the stored result (present on every response of this idempotent POST).",
                "schema": {
                  "type": "string",
                  "enum": [
                    "true",
                    "false"
                  ]
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RefundResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "description": "Idempotency key in flight (`idempotency_in_flight`) with `Retry-After`",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure, refund exceeds the remaining amount (`refund_exceeds_amount`) or invalid payment state (`invalid_state`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/payment-instruments": {
      "post": {
        "tags": [
          "Payment Instruments"
        ],
        "summary": "Register a payment instrument from a single-use vault token",
        "description": "PCI boundary: the browser-side capture surface (PA Secure Fields SDK → PA Locker) tokenizes PAN/CVV into a single-use `vault_token`. This endpoint registers the instrument in PA — the request struct carries NO card fields and cannot accept PAN/CVV; PA resolves the masked metadata (masked PAN, brand, expiry) from the vault itself. The vault token is a credential: it is consumed for the metadata lookup and stored as a reference only, never serialized back.\n\nRequires the `Idempotency-Key` header.",
        "operationId": "createPaymentInstrument",
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreatePaymentInstrumentRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Instrument registered. Idempotent replay: the same `Idempotency-Key` + body returns the ORIGINAL stored result — the same `201` status and body, header `Idempotent-Replayed: true`, no second instrument (a stored deterministic error problem replays with its original status and problem body).",
            "headers": {
              "Idempotent-Replayed": {
                "description": "`false` on a fresh execution, `true` on a replay of the stored result (present on every response of this idempotent POST).",
                "schema": {
                  "type": "string",
                  "enum": [
                    "true",
                    "false"
                  ]
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaymentInstrumentResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "description": "Idempotency key in flight (`idempotency_in_flight`) or this vault token is already registered as a payment instrument of the tenant (`vault_token_already_registered`)",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Unknown vault token (`vault_token_unknown`), unknown merchant (`unknown_merchant`), validation failure (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/payment-instruments/{id}": {
      "get": {
        "tags": [
          "Payment Instruments"
        ],
        "summary": "Fetch a payment instrument (masked view)",
        "description": "Returns masked card metadata only (masked PAN `****<last4>`, brand, optional expiry) and the instrument lifecycle status. No vault token is ever returned.",
        "operationId": "getPaymentInstrument",
        "parameters": [
          {
            "$ref": "#/components/parameters/InstrumentId"
          }
        ],
        "responses": {
          "200": {
            "description": "Masked instrument",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaymentInstrumentResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Instrument not found in this tenant (`instrument_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/payouts": {
      "post": {
        "tags": [
          "Payouts"
        ],
        "summary": "Create a payout",
        "description": "Creates a payout (card-based receiver by `instrument_id` in the MVP; masked receiver metadata only — PAN/CVV payloads are rejected). Payouts follow the approval-gate lifecycle: created payouts wait for an operator decision (`POST /v1/payouts/{id}/approve|decline`) before dispatch.\n\nThe whole surface is gated by the fail-closed `payouts_enabled` feature flag: while off, every payout route answers 404 `feature_disabled`.\n\nRequires the `Idempotency-Key` header.",
        "operationId": "createPayout",
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreatePayoutRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Payout created. Idempotent replay: the same `Idempotency-Key` + body returns the ORIGINAL stored result — the same `201` status and body, header `Idempotent-Replayed: true`, no second payout (a stored deterministic error problem replays with its original status and problem body).",
            "headers": {
              "Idempotent-Replayed": {
                "description": "`false` on a fresh execution, `true` on a replay of the stored result (present on every response of this idempotent POST).",
                "schema": {
                  "type": "string",
                  "enum": [
                    "true",
                    "false"
                  ]
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Payouts disabled for this deployment (`feature_disabled`) or merchant not found (`unknown_merchant`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Idempotency key in flight (`idempotency_in_flight`) with `Retry-After`",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request` — incl. PAN/CVV card data fields in the receiver/risk_context payload: the problem message names the offending field, e.g. `receiver must not contain card data fields (PAN/CVV)`; there is no separate card-data error code), unknown merchant (`unknown_merchant`), pre-flight limit failure (`limit_exceeded`) or idempotency key reuse (`idempotency_key_reuse`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      },
      "get": {
        "tags": [
          "Payouts"
        ],
        "summary": "List payouts (the console approval queue, PA-69)",
        "description": "The tenant payout list page (PA-69, research §5 P0): newest first, filter-scoped `total`, clamped page. The console approval queue filters `status=AWAITING_APPROVAL`; the gate actions stay the existing `POST /v1/payouts/{id}/approve|decline|cancel` endpoints (PA-27) — this read adds no second mutation surface. Same fail-closed `payouts_enabled` feature flag as the rest of the payout domain (404 `feature_disabled` while off). Read-only: no audit rows.",
        "operationId": "listPayouts",
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Optional payout-status filter (the canonical registry).",
            "schema": {
              "type": "string",
              "enum": [
                "CREATED",
                "AWAITING_APPROVAL",
                "APPROVED",
                "PROCESSING",
                "COMPLETED",
                "DECLINED",
                "FAILED_TECHNICAL",
                "CANCELLED",
                "UNKNOWN_PENDING_SYNC"
              ]
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size (clamped to 200).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 50,
              "maximum": 200
            }
          },
          {
            "name": "offset",
            "in": "query",
            "required": false,
            "description": "Page offset (0-based).",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Payout list page",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutListResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "404": {
            "description": "Payouts are not enabled for this tenant (`feature_disabled`, fail-closed)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/payouts/{id}": {
      "get": {
        "tags": [
          "Payouts"
        ],
        "summary": "Fetch a payout",
        "description": "Returns the payout aggregate: status, collapsed attempt summary, approval decisions (optimistic-concurrency `version` included). 404 `feature_disabled` while the feature flag is off.",
        "operationId": "getPayout",
        "parameters": [
          {
            "$ref": "#/components/parameters/PayoutId"
          }
        ],
        "responses": {
          "200": {
            "description": "Payout state",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Feature disabled (`feature_disabled`) or payout not found in this tenant (`payout_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/payouts/{id}/approve": {
      "post": {
        "tags": [
          "Payouts"
        ],
        "summary": "Approve a payout (approval gate)",
        "description": "Fixes the operator decision `APPROVED` under the configured approval policy (fail-closed gate). Idempotent: the same key replays the stored decision. Empty body allowed.",
        "operationId": "approvePayout",
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          },
          {
            "$ref": "#/components/parameters/PayoutId"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PayoutMutationRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Decision recorded / replayed",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Feature disabled (`feature_disabled`) or payout not found (`payout_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Idempotency key in flight (`idempotency_in_flight`) or a payout state that does not allow this transition (`invalid_state_transition` — incl. concurrent modification; RFC 7807, ADR-0004 §4.2 rule 6 — NOT stored as an idempotency result: a retry re-evaluates the current state)",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Idempotency key reuse (`idempotency_key_reuse`) or the approval-time limit re-check failure (`limit_exceeded`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/payouts/{id}/decline": {
      "post": {
        "tags": [
          "Payouts"
        ],
        "summary": "Decline a payout (approval gate)",
        "description": "Fixes the operator decision `DECLINED`. Idempotent. Empty body allowed; `reason` is optional.",
        "operationId": "declinePayout",
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          },
          {
            "$ref": "#/components/parameters/PayoutId"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PayoutMutationRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Decision recorded / replayed",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Feature disabled (`feature_disabled`) or payout not found (`payout_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Idempotency key in flight (`idempotency_in_flight`) or a payout state that does not allow this transition (`invalid_state_transition` — incl. concurrent modification; RFC 7807, ADR-0004 §4.2 rule 6 — NOT stored as an idempotency result: a retry re-evaluates the current state)",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Idempotency key reuse (`idempotency_key_reuse`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/payouts/{id}/cancel": {
      "post": {
        "tags": [
          "Payouts"
        ],
        "summary": "Cancel a payout before dispatch",
        "description": "Cancels a payout before dispatch (ADR-0004 §4.7.1). Idempotent. Empty body allowed.",
        "operationId": "cancelPayout",
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          },
          {
            "$ref": "#/components/parameters/PayoutId"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PayoutMutationRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Decision recorded / replayed",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Feature disabled (`feature_disabled`) or payout not found (`payout_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Idempotency key in flight (`idempotency_in_flight`) or a payout state that does not allow this transition (`invalid_state_transition` — incl. concurrent modification; RFC 7807, ADR-0004 §4.2 rule 6 — NOT stored as an idempotency result: a retry re-evaluates the current state)",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Idempotency key reuse (`idempotency_key_reuse`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/payouts": {
      "post": {
        "tags": [
          "Merchant Payouts"
        ],
        "summary": "Create a payout for this merchant",
        "description": "The MERCHANT-facing payout create (PA-83): the casino requests a payout for its own player. The receiver is a payment instrument OF THIS MERCHANT (`pin_…`) — an unknown or a sibling merchant's instrument is `422 unknown_instrument`; the player reference defaults to the instrument's ownership context when `customer_reference` is omitted.\n\nThe payout enters the SAME approval gate as the operator surface: with the default policy it is created `AWAITING_APPROVAL` and waits for the operator decision (`next_action.type = \"approval\"`). The PSP execution is the operator-side Phase 2.\n\nFail-closed gate (PA-97): the surface requires the tenant-level `payouts_enabled` gate AND the per-merchant `payouts_enabled` toggle — otherwise `422 payouts_not_enabled`.\n\nAuthorization: the admin (tenant) Bearer or the merchant-scoped key — a merchant key may only address ITS OWN merchant (a foreign path is a plain `404`).\n\nRequires the `Idempotency-Key` header.",
        "operationId": "createMerchantPayout",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MerchantCreatePayoutRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Payout created. Idempotent replay: the same `Idempotency-Key` + body returns the ORIGINAL stored result — the same `201` status and body, header `Idempotent-Replayed: true`, no second payout (a stored deterministic error problem replays with its original status and problem body).",
            "headers": {
              "Idempotent-Replayed": {
                "description": "`false` on a fresh execution, `true` on a replay of the stored result (present on every response of this idempotent POST).",
                "schema": {
                  "type": "string",
                  "enum": [
                    "true",
                    "false"
                  ]
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in the tenant (`merchant_not_found`) — for a merchant-scoped key also any foreign merchant path (a plain 404, the merchant-scope pattern).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Idempotency key in flight (`idempotency_in_flight`) with `Retry-After`",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Payouts not enabled for this merchant (`payouts_not_enabled`), validation failure (`invalid_request` — incl. PAN/CVV card data fields in the receiver/risk_context payload), unknown or foreign instrument (`unknown_instrument`), receiver instrument not eligible for payout (`instrument_not_payout_eligible` — the receiver accepts `ACTIVE`/`USED`, PA-87 payout-to-deposit-card), unknown player reference (`invalid_request` when neither the body nor the instrument carries one), pre-flight limit failure (`limit_exceeded`) or idempotency key reuse (`idempotency_key_reuse`), H2H raw-card receiver (PA-93: `receiver_card`): the H2H gate closed on any level (`h2h_not_enabled` — checked BEFORE validation), card validation (`invalid_card_number`, `invalid_card_expiry`, `card_expired`, `invalid_card_holder` — the receiver form carries NO cvc field), both receiver forms at once or neither (`invalid_request`), a receiver mask alongside `receiver_card` (`invalid_request`), missing explicit player reference on the receiver form (`invalid_request`). Raw-card receiver payouts draw from the same per-merchant H2H rate-limit bucket as raw-card deposits",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "get": {
        "tags": [
          "Merchant Payouts"
        ],
        "summary": "List this merchant's payouts",
        "description": "The merchant's own payout list (PA-83) — newest first, filter-scoped `total`, clamped page (default 50, capped 200). Authorization: the admin (tenant) Bearer or the merchant-scoped key (a foreign merchant path is a plain `404`). Fail-closed: `422 payouts_not_enabled` while the merchant gate is off.",
        "operationId": "listMerchantPayouts",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Optional payout-status filter (the canonical registry).",
            "schema": {
              "type": "string",
              "enum": [
                "CREATED",
                "AWAITING_APPROVAL",
                "APPROVED",
                "PROCESSING",
                "COMPLETED",
                "DECLINED",
                "FAILED_TECHNICAL",
                "CANCELLED",
                "UNKNOWN_PENDING_SYNC"
              ]
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size (clamped to 200).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 50,
              "maximum": 200
            }
          },
          {
            "name": "offset",
            "in": "query",
            "required": false,
            "description": "Page offset (0-based).",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The merchant's payout page.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantPayoutListResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in the tenant (`merchant_not_found`) — for a merchant-scoped key also any foreign merchant path.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Payouts not enabled for this merchant (`payouts_not_enabled`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/payouts/{payout_id}": {
      "get": {
        "tags": [
          "Merchant Payouts"
        ],
        "summary": "Read one of this merchant's payouts",
        "description": "The payout state of the merchant's own payout (PA-83): status, amounts, attempts summary, approval decisions and `next_action` (`approval` while the operator gate is active). The payout must belong to the path merchant — a sibling merchant's payout (or a foreign id) is a plain `404` (`payout_not_found`), never a 403. Fail-closed: `422 payouts_not_enabled` while the merchant gate is off.",
        "operationId": "getMerchantPayout",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "$ref": "#/components/parameters/PayoutId"
          }
        ],
        "responses": {
          "200": {
            "description": "The payout projection (the same shape as the operator read).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found (`merchant_not_found`) or the payout does not belong to this merchant (`payout_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Payouts not enabled for this merchant (`payouts_not_enabled`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/payouts/{payout_id}/cancel": {
      "post": {
        "tags": [
          "Merchant Payouts"
        ],
        "summary": "Cancel this merchant's payout request",
        "description": "The MERCHANT cancel (PA-83): the casino withdraws its own payout request while it is still `CREATED`/`AWAITING_APPROVAL` — before the operator decision. STRICTLY NARROWER than the operator cancel: an operator-APPROVED payout answers `409 payout_not_cancellable` (the execution flow belongs to the operator). The released limit reservations are freed (proven non-execution). Idempotent; empty body allowed (`reason` optional).",
        "operationId": "cancelMerchantPayout",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "$ref": "#/components/parameters/PayoutId"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PayoutMutationRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The payout is `CANCELLED` (or the replayed stored result).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found (`merchant_not_found`) or the payout does not belong to this merchant (`payout_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Idempotency key in flight (`idempotency_in_flight`), a payout state outside the merchant-cancellable range (`payout_not_cancellable` — e.g. the payout was already approved by the operator) or a concurrent modification (`invalid_state_transition`).",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Payouts not enabled for this merchant (`payouts_not_enabled`) or idempotency key reuse (`idempotency_key_reuse`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants": {
      "post": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Create a merchant",
        "description": "Creates the merchant with its onboarding profile (default currency scope of the routing configuration). The routing configuration starts empty — route targets are added explicitly. Audited as `create_merchant` in the same transaction as the change.",
        "operationId": "createMerchant",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateMerchantRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Merchant created",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CreateMerchantResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "422": {
            "description": "Validation failure (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      },
      "get": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "List the tenant merchants (admin console registry, PA-69)",
        "description": "The server-side merchant registry of the tenant (PA-69, the research doc `admin-console-research.md` §5 P0 gap): newest first, strictly tenant-scoped, with per-merchant provider (PA-59 execution model + connector status) and route-target lifecycle (PA-58) summaries. Optional `with_stats=1` attaches the 7d turnover snapshot per merchant (the PA-65 stats aggregate — GROSS EUR turnover of the approved family in minor units, previous-period delta, approval ratio; one aggregate query per page row). Replaces the PA-52 `localStorage` registry: the server is the source of truth.\n\n`q` is a substring filter over the name and the `mer_`-prefixed id (`%`/`_` are escaped — a literal match). Read-only: no audit rows (the console polls it).",
        "operationId": "listMerchants",
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size (clamped to 200).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 50,
              "maximum": 200
            }
          },
          {
            "name": "offset",
            "in": "query",
            "required": false,
            "description": "Page offset (0-based).",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            }
          },
          {
            "name": "q",
            "in": "query",
            "required": false,
            "description": "Substring filter over the merchant name and the `mer_…` id.",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "with_stats",
            "in": "query",
            "required": false,
            "description": "Attach the 7d turnover snapshot per merchant (`1|true|yes` / `0|false|no`).",
            "schema": {
              "type": "string",
              "enum": [
                "1",
                "true",
                "yes",
                "0",
                "false",
                "no"
              ]
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Merchant registry page",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantListResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}": {
      "get": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Fetch the merchant configuration",
        "description": "Full configuration of the merchant: onboarding profile, providers (with MIDs), route targets with filters and capability snapshot, registered webhook endpoint (URL only — the signing secret is never returned by a read).",
        "operationId": "getMerchant",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "200": {
            "description": "Merchant configuration",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantConfigResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      },
      "patch": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Update the merchant profile",
        "description": "PA-140: PARTIAL update of the EDITABLE merchant profile. Only `name`, `country`, `currencies` and `legal_entity` are editable here — the API keys, the webhook URL/secret, the h2h and payouts gates and the STD threshold keep their dedicated endpoints (sending one of them answers `422 invalid_request` with `details.fields`, it is never silently ignored).\n\nAn ABSENT field keeps its stored value; an explicit `null` RESETS `country`/`legal_entity` (the other two are not nullable). A RESET is `null` only: an empty or blank `country` string is `422 invalid_request` (`details.field=country`), never a silent clear. `name` is trimmed and bounded to 1..120 characters, `country` is an ISO 3166-1 alpha-2 code (upper-cased), `currencies` is a non-empty duplicate-free list of ISO 4217 alpha-3 codes (upper-cased), `legal_entity` is a JSON object. A patch that changes nothing answers `200` and writes NO audit event.\n\nThe change and its `merchant.updated` audit event (details: `before`/`after` of the CHANGED fields only) are committed in ONE transaction. The response is the same projection as `GET /v1/merchants/{id}`.",
        "operationId": "updateMerchant",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateMerchantRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated merchant configuration (the `GET /v1/merchants/{id}` projection)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantConfigResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`) — the merchant profile is an operator surface.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`). A merchant of another tenant is indistinguishable from a missing one.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request`) with `details.field` (`name` / `country` / `currencies` / `legal_entity`; an empty or blank `country` is a validation error — only `null` clears it), `details.fields` for the non-editable fields, or an empty patch.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      },
      "delete": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Delete an EMPTY merchant",
        "description": "PA-140: deletes ONE merchant of the tenant. Allowed ONLY while the merchant owns no transaction or notification history — this is a real `DELETE`, not an archive, so the guard is the point:\n\n- HISTORY (`payments`, `payouts`, `payment_instruments`, `webhook_deliveries`) → `409 merchant_not_empty`. Those rows are the ledger and the delivery evidence; the response `details` carries the full dependency inventory (`dependencies`), the blocking subset (`history`/`blocking`), the configuration that would have been removed (`configuration` — every table of the delete plan, including the child rows: providers and their MIDs, route targets and their method bindings, PSP connections, terminals, their method bindings and credential envelopes, routing cascades and their routes, the legacy enablement projection, grace-window key hashes and merchant payout limits — plus the `configuration_total` row count). Nothing is deleted.\n- CONFIGURATION is removed explicitly, deepest first, each statement scoped to THIS merchant — never through an FK cascade — and then the merchant row itself.\n\nEverything happens in ONE transaction with the `merchant.deleted` audit event (details: `id`, `name`, `configuration_rows_removed`): either the merchant is gone and the journal records it, or nothing changed. A foreign/unknown merchant is `404 merchant_not_found`; a second call on a deleted merchant is the same `404`, never a phantom `204`.\n\nLoss of the race with a concurrent payment/configuration write is a retryable `409 merchant_busy` (`details.reason=concurrent_write`, `details.retryable=true`, the violated FK `constraint`): nothing was removed and the same call succeeds on retry.",
        "operationId": "deleteMerchant",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "204": {
            "description": "Merchant deleted (no body). Audited as `merchant.deleted`."
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`) — deletion is an operator surface.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`) — including a repeat call on an already deleted merchant.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`merchant_not_empty` — the merchant owns payment/payout history (`details.dependencies`, `details.history`, `details.blocking`, `details.configuration`, `details.configuration_total`); nothing is deleted. OR `merchant_busy` — a concurrent writer won the race while the delete was running (`details.reason=concurrent_write`, `details.retryable=true`, `details.constraint`); nothing is deleted, retry the call.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/providers": {
      "post": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Link a provider (MID) to the merchant",
        "description": "Links one provider account (MID) to the merchant. The provider (connector) is reused when it already exists for the merchant, otherwise it is created first. `credentials_ref` is a PA reference only — connector credentials never enter PA. Audited as `create_provider` + `create_provider_account`.",
        "operationId": "addMerchantProvider",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AddProviderRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Provider account linked",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AddProviderResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      },
      "get": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "List the merchant's effective PSP set (PA-105, operator-locked rows hidden for the merchant)",
        "description": "Returns the EFFECTIVE PSP set of the merchant: one row per payment provider the operator actually configured for this merchant (distinct connector codes over its route targets), joined with the merchant's per-provider enablement overrides. `enabled=false` = the merchant disabled this PSP (an explicit override row; its route targets are excluded from the routing eligibility of this merchant's NEW payments — `422 no_eligible_route` when nothing else remains). `enabled=true` = enabled — by default (no override row: the operator set applies as-is) or by an explicit re-enable. A merchant-scoped key reads its own merchant; the admin key reads any merchant of the tenant; a foreign merchant is a plain 404. PA-105 granularity: a multiplexing PSP (Apcopay, PA-112) is enumerated per sub-provider — one row per `provider_routing.bank_code` of its Route Targets plus the master row (`sub_provider` absent) for the targets without provider routing; the master row switches the whole connector. PA-116/PA-117: an OPERATOR-enforced disable (`operator_locked=true`, the admin toggle with `enabled=false, operator_locked=true`) never reaches the merchant-scoped key, while a SOFT admin disable (`enabled=false` without the lock field) stays visible to the merchant as a disabled row it may re-enable: the locked rows (and every row of a connector whose master row is locked) are filtered out of the merchant-scope answer entirely — the PSP is simply not part of the merchant's world. The admin scope lists ALL rows, each locked one carrying `operator_locked: true`.",
        "operationId": "listMerchantProviders",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "200": {
            "description": "The merchant's effective PSP set",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantProvidersResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/route-targets": {
      "post": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Add a route target",
        "description": "Adds a Route Target (one routable terminal: MID + priority + weight + filters + capability snapshot). The MID must belong to a provider OF the merchant (scoped lookup, 404 otherwise). Audited as `update_routing` on the merchant.",
        "operationId": "addMerchantRouteTarget",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AddRouteTargetRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Route target created",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AddRouteTargetResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant or provider account not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/psp-catalog": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List the global PSP catalog",
        "description": "The global PSP catalog (operator-owned reference data, NO credentials). Optional `integration_status` query filter (DRAFT|INTEGRATING|ACTIVE|DEPRECATED|RETIRED). PA-136 live-fix (W6): every entry carries its `methods` (the `psp_methods` restrictions joined with `payment_methods`), attached with ONE batched query per page — the catalog, routing and manage pages render the methods of each PSP without a per-PSP round-trip. The list is empty (`methods: []`) for a PSP whose restrictions were never configured. PA-148: every entry also carries the auth-scheme scope and parameters (`applies_to`, `auth_header`, `signature_params`) — light fields of the definition, so the catalog/API-Auth pages need no per-PSP round-trip.",
        "operationId": "listPspCatalog",
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Catalog list."
          }
        }
      },
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Create a catalog PSP",
        "description": "Creates a catalog PSP (admin-only). `technical_id` (= `providers.connector_code`) is unique; `integration_status` starts DRAFT. PA-148: `applies_to`, `auth_header` and `signature_params` are part of the create body (values validated, `422` with `details.field`). Audited `psp_catalog.updated`.",
        "operationId": "createPspCatalog",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "technical_id",
                  "name"
                ],
                "properties": {
                  "technical_id": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  },
                  "description": {
                    "type": "string"
                  },
                  "logo_url": {
                    "type": "string"
                  },
                  "terminal_policy": {
                    "type": "string",
                    "enum": [
                      "NONE",
                      "SHARED",
                      "MULTIPLE"
                    ],
                    "default": "MULTIPLE"
                  },
                  "auth_scheme": {
                    "type": "string",
                    "enum": [
                      "private_key_only",
                      "merchant_private",
                      "basic",
                      "api_key",
                      "bearer",
                      "oauth",
                      "hmac",
                      "custom"
                    ]
                  },
                  "adapter_key": {
                    "type": "string"
                  },
                  "version": {
                    "type": "string"
                  },
                  "environments": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    },
                    "default": [
                      "sandbox",
                      "live"
                    ]
                  },
                  "applies_to": {
                    "type": "array",
                    "minItems": 1,
                    "items": {
                      "type": "string",
                      "enum": [
                        "payments",
                        "payouts",
                        "refunds"
                      ]
                    },
                    "default": [
                      "payments"
                    ],
                    "description": "PA-148: operations the API-auth scheme covers; absent = `[\"payments\"]` (the column default, i.e. the historical single-scheme scope)."
                  },
                  "auth_header": {
                    "type": "string",
                    "nullable": true,
                    "maxLength": 64,
                    "pattern": "^[A-Za-z0-9-]+$",
                    "description": "PA-148: header carrying the signature/key (`Authorization`, `X-Api-Key`, …); absent = not configured."
                  },
                  "signature_params": {
                    "type": "string",
                    "nullable": true,
                    "maxLength": 128,
                    "description": "PA-148: what the signature is computed over (`payload+timestamp`); absent = not configured."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "201": {
            "description": "Created catalog PSP."
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "technical_id already exists.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failed.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Get one catalog PSP with templates + credential fields",
        "description": "One catalog PSP plus its terminal templates and each template's credential field definitions (the dynamic credential schema — never values). PA-136 live-fix (W6): the flattened entry carries the PSP's `methods` (the `psp_methods` restrictions joined with `payment_methods`) — exactly one field, never a second `methods` key beside the flattened entry. **PA-143:** every `terminal_templates[]` item also carries `method_ids[]` and the resolved `methods[]` (`{id, code, name}`) next to its `credential_field_definitions[]` (the «Edit Method Binding» drawer needs the codes to tell whether a template really serves a method), plus `code`/`environment`. PA-148: the flattened entry carries `applies_to` / `auth_header` / `signature_params`, the auth-scheme scope and parameters of the definition.",
        "operationId": "getPspCatalog",
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Catalog PSP detail."
          },
          "404": {
            "description": "Catalog PSP not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "patch": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Update the general PSP definition",
        "description": "PA-136 (Admin v2 → Configure → Overview → Save General / Publish). Updates the operator-owned definition of a catalog PSP: name/description/logo, adapter_key, auth_scheme, terminal_policy, version, environments, integration_status and — since PA-148 — applies_to, auth_header, signature_params. Every field is optional — an absent field is unchanged, an explicit `null` clears a nullable one.\n\n`technical_id` is IMMUTABLE: it is the stable link to the executing layer (`providers.connector_code`); the field is not part of the body and an unknown key is ignored by the request parser (documented instead of rejected).\n\nValidations: `terminal_policy ∈ NONE|SHARED|MULTIPLE`; `auth_scheme` from the 8 presets (empty string clears it); `environments ⊆ {sandbox,live}` and non-empty. `integration_status` follows DRAFT → INTEGRATING → ACTIVE → DEPRECATED → RETIRED (INTEGRATING → DRAFT is the revision rollback; nothing leaves RETIRED) — otherwise `409 invalid_status_transition`. ACTIVE requires at least one PSP method restriction — otherwise `409 definition_incomplete`. A `terminal_policy` change with existing merchant connections is `409 policy_conflict` (the problem `details` carry `merchant_ids`, connection/terminal/template counters and `force_supported`) unless `?force=1`; force only admits changes the EXISTING data already satisfies.",
        "operationId": "updatePspCatalogDefinition",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "force",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "1",
                "0"
              ]
            },
            "description": "Acknowledge the guarded mutation (`1`/`true`/`yes`). For `terminal_policy` it admits the change once the EXISTING terminal data is compatible with the NEW policy; it never deletes terminals or routes."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdatePspCatalogRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "Catalog PSP not found (`psp_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Definition conflict: `invalid_status_transition`, `definition_incomplete` or `policy_conflict`. The problem `details` carry the structured context (`from`/`to`, affected `merchant_ids`, counters, `force_supported`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure: `invalid_request`, `invalid_terminal_policy`, `invalid_auth_scheme`, `invalid_environment`, `invalid_integration_status`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "The updated catalog PSP (the same shape as the list entry).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspCatalogEntry"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/disable": {
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Disable a PSP globally (platform-wide kill switch)",
        "description": "PA-136 (M-1): switches the catalog PSP OFF for the WHOLE platform (`psp_catalog.globally_disabled = true`, migration 0043). While the flag is set, every merchant connection/route of this PSP is evaluated as blocked (`effective_status`/routing-preview reason `psp_blocked`), enabling or restoring a connection answers `409 psp_disabled_globally`, and the connection detail carries the `psp_disabled_globally` warning.\n\nNOTHING is deleted — connections, terminals, routes and credentials stay intact, and the mirrored `enable` restores the previous behavior exactly. IDEMPOTENT: a repeated call answers `200` with the same entry and records no second audit event.\n\nThis is the GLOBAL AVAILABILITY flag, not the definition lifecycle: `integration_status` (PATCH `/v1/psp-catalog/{id}`) is never moved, so an ACTIVE definition may be globally disabled and a DRAFT one may be enabled. Admin-only; audited `psp_catalog.disabled_globally` with before/after (and the optional `reason`) when the value actually changes.",
        "operationId": "disablePspCatalog",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PspGlobalAvailabilityRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The catalog PSP with `globally_disabled: true`.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspCatalogEntry"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Catalog PSP not found (`psp_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request`: the path id is not a UUID, the reason is too long).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/enable": {
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Enable a globally disabled PSP",
        "description": "PA-136 (M-1): clears the platform-wide kill switch (`psp_catalog.globally_disabled = false`). The connections/terminals/routes were never touched by the disable, so after this call they evaluate exactly as before it (a connection keeps its OWN local status — this endpoint does not enable connections).\n\nIDEMPOTENT: a repeated call answers `200` with the same entry and records no second audit event. NO credential gate applies here — `409 credentials_missing` belongs to the CONNECTION enable (`PATCH /v1/merchants/{id}/psp-connections/{conn}`); the global flag has no credential semantics. Admin-only; audited `psp_catalog.enabled_globally` with before/after (and the optional `reason`) when the value actually changes.",
        "operationId": "enablePspCatalog",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PspGlobalAvailabilityRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The catalog PSP with `globally_disabled: false`.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspCatalogEntry"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Catalog PSP not found (`psp_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request`: the path id is not a UUID, the reason is too long).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/impact": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Impact of a global PSP disable",
        "description": "PA-136 (M-1): the data footprint of one catalog PSP — how many merchants, connections, terminals, routes and method restrictions a global disable would affect.\n\n`merchants`/`connections`/`terminals` count the LIVE (non-archived) rows; `routes` counts the routes structurally bound to the PSP (route → terminal → connection) — ACCOUNT-LEVEL routes carry no PSP reference by design (ADR-0009 §6.1) and are therefore not attributable to one PSP; `methods` is the PSP's restriction-row count. Counters ONLY: no record and no credential is ever returned. Admin-only and side-effect free (no audit event).",
        "operationId": "getPspCatalogImpact",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The impact counters.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspGlobalImpactResponse"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Catalog PSP not found (`psp_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/validate": {
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Validate a PSP definition (read-only)",
        "description": "PA-136 live-fix (W6): the read-only definition check behind the Admin v2 «Перевірити definition» button. Runs the REAL checks of the catalog PSP definition — `auth_scheme` preset, `adapter_key`, `environments`, the `psp_methods` restrictions (currencies/countries/amount bounds), the dynamic credential schema (`merchant_account` fields, empty/duplicate `key`s, `webhook` fields without a webhook profile) and the terminal policy against the templates/methods actually configured.\n\nThe response is `{ok, errors, warnings}`: `ok` is `true` ONLY when `errors` is empty (that hard invariant is what the publish gate relies on), `warnings` never block. Every finding is `{code, path, message}` — `code` is the stable identifier the UI keys on, `path` points at the definition node, `message` is the operator-facing sentence. Both lists are sorted by `(code, path)`.\n\nStable `code`s: errors — `missing_auth_scheme`, `invalid_auth_scheme`, `no_environments`, `invalid_environment`, `no_methods`, `invalid_currency`, `invalid_country`, `invalid_amount_range`, `empty_field_key`, `duplicate_field_key`, `policy_forbids_templates`, `policy_single_template`; warnings — `missing_adapter`, `no_account_fields`, `webhook_fields_without_profile`, `empty_currencies`, `empty_countries`, `policy_without_templates`, `template_without_methods`.\n\nA definition without a single method restriction is ALWAYS an error (`no_methods`) — including on a DRAFT, because publish must be blocked there too, not only once the PSP is ACTIVE.\n\nAdmin-only, NO audit row (nothing is written) and no side effects. An absent body is valid, `{}` is valid.",
        "operationId": "validatePspCatalogDefinition",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ValidatePspDefinitionRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The definition validation result.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspDefinitionValidation"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Catalog PSP not found (`psp_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request`: the path id is not a UUID).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/publish": {
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Publish (activate) a PSP definition",
        "description": "PA-136 live-fix (W6): the publish gate of the Admin v2 Configure → Overview page. Runs EXACTLY the same checks as `POST /v1/psp-catalog/{id}/validate`; any error answers `409 definition_incomplete` with the findings in `details.errors` (plus the non-blocking `details.warnings`), so the UI renders precisely what blocks the button. On success the definition moves to `integration_status = ACTIVE` through the existing lifecycle machine (`DRAFT → INTEGRATING → ACTIVE`, `INTEGRATING → ACTIVE`) and the call answers `200` with the settled catalog entry (without `methods` — the write-response convention).\n\nIDEMPOTENT: publishing an already ACTIVE definition answers `200` with the same entry and records NO second audit event. `DEPRECATED`/`RETIRED` definitions are never re-published (`409 invalid_status_transition` — the lifecycle is one-way).\n\nAdmin-only; audited `psp_catalog.published` with the non-secret before/after snapshots, the transitions applied (`via`) and the warnings. An absent body is valid, `{}` is valid.",
        "operationId": "publishPspCatalogDefinition",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ValidatePspDefinitionRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The published catalog PSP (`integration_status: ACTIVE`). Idempotent for an already ACTIVE definition.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspCatalogEntry"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Catalog PSP not found (`psp_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "The definition cannot be published: `definition_incomplete` (the blocking errors are in `details.errors`, the non-blocking findings in `details.warnings`), or `invalid_status_transition` (a DEPRECATED/RETIRED definition is never re-activated).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request`: the path id is not a UUID).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/payment-methods": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List the global payment-method registry",
        "description": "The global payment-method dictionary (code/name/category/supported_operations/status/description). Optional `category` filter (CARD|APPLE_PAY|GOOGLE_PAY|OPEN_BANKING|BANK_TRANSFER) and, since PA-136, the lifecycle `status` filter (ACTIVE|DEPRECATED|HIDDEN).",
        "operationId": "listPaymentMethods",
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Method registry.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaymentMethodListResponse"
                }
              }
            }
          }
        },
        "parameters": [
          {
            "name": "category",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "CARD",
                "APPLE_PAY",
                "GOOGLE_PAY",
                "OPEN_BANKING",
                "BANK_TRANSFER"
              ]
            },
            "description": "Routing category filter."
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "ACTIVE",
                "DEPRECATED",
                "HIDDEN"
              ]
            },
            "description": "Lifecycle status filter (PA-136)."
          }
        ]
      },
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Register a global payment method",
        "description": "PA-136 (Admin v2 → Configure → Payment Methods → + New Global Method). `code` is the stable routing key: it is normalized to UPPER_SNAKE and unique case-insensitively; `name` is unique case-insensitively too (duplicates answer 409 with the offending `field`). `routing_category` is one of the five cascade buckets, `supported_operations` is a non-empty subset of `{deposit,payout,refund}`. A new method starts ACTIVE. Audited `payment_method.created`.",
        "operationId": "createPaymentMethod",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreatePaymentMethodRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "409": {
            "description": "`payment_method_code_exists` or `payment_method_name_exists` (case-insensitive).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure: `invalid_request`, `invalid_payment_method_code`, `invalid_routing_category`, `invalid_supported_operations`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "201": {
            "description": "The registered method definition.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaymentMethodDefinition"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/webhook-profiles": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List a PSP's webhook verification profiles",
        "description": "The inbound webhook verification profiles of a catalog PSP (ADR-0009 §3.5).",
        "operationId": "listWebhookProfiles",
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Webhook profiles.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookProfileListResponse"
                }
              }
            }
          },
          "404": {
            "description": "Catalog PSP not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Create a webhook verification profile",
        "description": "Creates one webhook verification profile for the PSP (admin-only). UNIQUE (psp_id, verifier_type) — one profile per strategy. Audited webhook_profile.created.",
        "operationId": "createWebhookProfile",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateWebhookProfileRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "201": {
            "description": "Created webhook profile.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookProfile"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Catalog PSP not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "webhook_profile_already_exists.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failed.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/webhook-profiles/{profile_id}": {
      "put": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Update a webhook verification profile",
        "description": "Full replace of a profile's non-identity fields (admin-only). Audited webhook_profile.updated.",
        "operationId": "updateWebhookProfile",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateWebhookProfileRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Updated webhook profile.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookProfile"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Webhook profile not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Delete a webhook verification profile",
        "description": "Removes a webhook verification profile (admin-only). Audited webhook_profile.removed.",
        "operationId": "deleteWebhookProfile",
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "204": {
            "description": "Deleted."
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Webhook profile not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/methods": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List a PSP's method restrictions",
        "description": "The PSP's global method restrictions (currencies/countries/min/max/transaction_type/availability) joined with the payment-method dictionary.",
        "operationId": "listPspMethods",
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Method restrictions.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspMethodListResponse"
                }
              }
            }
          },
          "404": {
            "description": "Catalog PSP not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Upsert a PSP method restriction",
        "description": "Adds/updates one restriction row per (method, transaction_type). Admin-only, audited `psp_method.updated`.",
        "operationId": "createPspMethod",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpsertPspMethodRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "201": {
            "description": "Upserted method restriction.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspMethod"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failed.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "put": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Upsert a PSP method restriction (idempotent)",
        "description": "Same idempotent upsert as POST.",
        "operationId": "updatePspMethod",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpsertPspMethodRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Upserted method restriction.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspMethod"
                }
              }
            }
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failed.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/methods/{psp_method_id}": {
      "delete": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Remove a PSP method restriction",
        "description": "Removes one restriction row. Admin-only, audited `psp_method.updated`.",
        "operationId": "deletePspMethod",
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "204": {
            "description": "Deleted."
          },
          "403": {
            "description": "Merchant-scoped key (admin-only).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "PSP method not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/psp-connections": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List a merchant's PSP connections",
        "description": "The merchant's connections to catalog PSPs, each with its terminals. Credentials are NEVER returned. PA-150: every element also carries `credentials` — the honest state of the connection (`schema_defined`, `fields_total`, `fields_configured`, `envelope_present`, `execution_binding.route_targets[]`/`has_mca_ref`): it explains WHY the API & Webhook tab is empty (no field schema in the PSP catalog, or execution through a HyperSwitch MCA that holds the PSP keys) instead of leaving an empty form. The external MCA reference value is never returned — only its presence (`has_mca_ref`).",
        "operationId": "listMerchantPspConnections",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Connections with terminals."
          }
        }
      },
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Connect a merchant to a catalog PSP",
        "description": "Connects the merchant to a catalog PSP (`psp_id`); `status` starts `draft` (fail-closed). Audited `merchant.psp_connected`.",
        "operationId": "createMerchantPspConnection",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "psp_id"
                ],
                "properties": {
                  "psp_id": {
                    "type": "string",
                    "format": "uuid"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "201": {
            "description": "Created connection."
          },
          "404": {
            "description": "Catalog PSP not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Connection already exists.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failed.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/psp-connections/{conn}": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Get one merchant PSP connection with terminals",
        "description": "One merchant connection with its terminals. Credentials are NEVER returned. PA-150: the projection also carries `credentials` — `schema_defined` (the PSP catalog has at least one credential field definition), `fields_total`/`fields_configured` (catalog fields vs stored values of this connection), `envelope_present` (does PA hold sealed credentials for it) and `execution_binding` (`route_targets[]` of the same connector code with `mid_label`/`has_mca_ref`, plus the aggregate `has_mca_ref`). `has_mca_ref: true` means the PSP keys live in the HyperSwitch MCA (`provider_accounts.external_mca_ref`), not in PA. Additive: every other field keeps its shape.",
        "operationId": "getMerchantPspConnection",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Connection with terminals."
          },
          "404": {
            "description": "Connection not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "patch": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Change a connection's local status/environment",
        "description": "Sets the local status of the merchant's connection (`enabled|available|blocked|hidden|draft`) and/or its `environment`. Transition rules: draft -> available/enabled; enabled <-> available; blocked/hidden are operator-only; leaving blocked/hidden for enabled requires valid credentials (`409 credentials_missing` — the `merchant_account`/`operation_specific` scopes only, a required `webhook` field never blocks) AND a PSP that is not globally disabled (`409 psp_disabled_globally`); a merchant key on an operator-locked connection answers `403 provider_locked_by_operator`. Audited `merchant_connection.status_changed` with before/after.",
        "operationId": "updateMerchantPspConnection",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "status": {
                    "type": "string",
                    "enum": [
                      "enabled",
                      "available",
                      "blocked",
                      "hidden",
                      "draft"
                    ]
                  },
                  "environment": {
                    "type": "string",
                    "enum": [
                      "sandbox",
                      "live"
                    ]
                  },
                  "reason": {
                    "type": "string",
                    "maxLength": 500
                  }
                }
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The updated connection detail."
          },
          "403": {
            "description": "Operator-only transition or a locked connection.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Connection not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Invalid transition, archived connection or missing credentials.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Invalid status/environment.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Archive a PSP connection (soft delete)",
        "description": "Soft-archives the connection and its terminals: nothing is deleted from the payment history or the audit trail. The routes bound to the connection's terminals are removed and their ids reported. Idempotent. Admin-only. Audited `merchant_connection.archived`.",
        "operationId": "archiveMerchantPspConnection",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Archived terminal/route counts."
          },
          "403": {
            "description": "Admin key required.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Connection not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/terminals": {
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Create a merchant terminal (envelope-encrypted credentials)",
        "description": "Creates a terminal of a catalog template. The owning connection is derived from the template's PSP. Credentials are validated against required fields and envelope-encrypted (AES-256-GCM; fail-closed `422 kek_not_configured` without a KEK). Audited `merchant.terminal_created` (fingerprint only). The name must be unique per (connection, template) among LIVE terminals only: an ARCHIVED terminal's name is reusable, and a clash with a live terminal answers `409 terminal_name_exists` (detail carries `connection_id`, `terminal_template_id`, `name`).",
        "operationId": "createMerchantTerminal",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "terminal_template_id",
                  "name"
                ],
                "properties": {
                  "terminal_template_id": {
                    "type": "string",
                    "format": "uuid"
                  },
                  "name": {
                    "type": "string",
                    "description": "Terminal name, unique per (connection, template) among LIVE terminals only — an ARCHIVED terminal's name can be reused; a clash with a live terminal answers `409 terminal_name_exists`."
                  },
                  "credentials": {
                    "type": "object",
                    "additionalProperties": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "201": {
            "description": "Created terminal (credentials_present + fingerprint, never the value)."
          },
          "404": {
            "description": "Terminal template not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "terminal_name_exists — the (connection, template, name) key is already taken by a LIVE terminal; an ARCHIVED terminal's name is reusable.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "kek_not_configured / terminal_template_singleton / missing_required_credential / psp_connection_not_found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List every terminal of the merchant",
        "description": "Every terminal of the merchant across all connections (archived ones included, marked by `archived_at`). Credentials are never returned.",
        "operationId": "listMerchantTerminals",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The merchant's terminals."
          }
        }
      }
    },
    "/v1/merchants/{id}/routing-cascades/{category}": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Get a merchant's routing cascade",
        "description": "The merchant's deposit cascade for a method category plus its ordered routes. `excluded[].reason` names the structural gate that stops a route: `connection_not_enabled` (the connection is not `enabled` — `available`, `blocked` or `draft` — and is not archived: a LOCAL connection state, spelled exactly like the routing decision log), `psp_blocked` (a PSP-level verdict: the catalog PSP is switched off globally by the operator or the connection is `hidden`), `terminal_disabled`, `method_hidden`, `route_disabled`, `missing_credentials`, `disconnected` (the connection is archived). `effective_status` keeps the coarse derived label — `blocked_by_psp` for any non-enabled connection, `hidden_by_psp` for a hidden one. The query-dependent reasons (`currency_unsupported`, `geo_unsupported`, `amount_out_of_range`, `operation_not_supported`) belong to the routing preview, which resolves this same structural gate first.",
        "operationId": "getRoutingCascade",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Cascade with ordered routes."
          },
          "404": {
            "description": "Cascade not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Invalid method_category.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "put": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Reorder a merchant's routing cascade (Drag&Drop)",
        "description": "Reorders the cascade: the body is the array of route ids in the NEW order; priorities are renumbered `(index+1)*10` atomically.",
        "operationId": "reorderRoutingCascade",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "array",
                "items": {
                  "type": "integer",
                  "format": "int64"
                }
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Cascade with reordered routes."
          },
          "404": {
            "description": "Cascade not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Invalid category or route id set.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/routing-cascades/{category}/routes": {
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Add a route to a routing cascade",
        "description": "Adds a route to the cascade (priority appended at the end). Validates the method category vs the cascade and the method vs the terminal; a NULL `merchant_terminal_id` is an account-level route (terminal_policy=NONE) whose EXECUTING Route Target is `route_target_id` (PA-137) — the two bindings are mutually exclusive (`422 invalid_request` when both are sent) and an explicit Route Target must belong to this merchant (`404 route_target_not_found`). An archived terminal (or its archived connection) is refused with `409 terminal_archived` — an archived terminal is not a routable target. The query `segment` (≤64, `[a-z0-9_-]`) creates/uses the segmented cascade and is validated against the same alphabet the payments request enforces (`422 invalid_request` otherwise). Audited `routing.route_added`.",
        "operationId": "addRoutingCascadeRoute",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AddRouteRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "201": {
            "description": "Created route.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RoutingCascadeRoute"
                }
              }
            }
          },
          "404": {
            "description": "Method/terminal not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`terminal_archived` — the terminal (or its connection) is archived and cannot serve a route.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Category mismatch / method not supported / validation.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/routing-cascades/{category}/routes/{route_id}": {
      "delete": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Remove a route from a routing cascade",
        "description": "Removes a route from its cascade (the terminal/credentials are NOT touched). Audited `routing.route_removed`.",
        "operationId": "deleteRoutingCascadeRoute",
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "204": {
            "description": "Deleted."
          },
          "404": {
            "description": "Cascade route not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "patch": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Edit a cascade route",
        "description": "Route-local `status` (`enabled|disabled|blocked|hidden`) and `visibility` (`visible|hidden`), the terminal binding (`merchant_terminal_id`; `null` makes it an account-level route) and/or the method. The terminal must belong to the merchant and its template must serve the method (`409 incompatible_binding`); one account-level route per (cascade, method) (`409 routing_route_already_exists`). Admin-only; audited `routing_route.updated`.",
        "operationId": "updateRoutingCascadeRoute",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "category",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "enum": [
                "CARD",
                "APPLE_PAY",
                "GOOGLE_PAY",
                "OPEN_BANKING",
                "BANK_TRANSFER"
              ]
            }
          },
          {
            "name": "route_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "integer",
              "format": "int64"
            }
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "status": {
                    "type": "string",
                    "enum": [
                      "enabled",
                      "disabled",
                      "blocked",
                      "hidden"
                    ]
                  },
                  "visibility": {
                    "type": "string",
                    "enum": [
                      "visible",
                      "hidden"
                    ]
                  },
                  "merchant_terminal_id": {
                    "type": "integer",
                    "format": "int64",
                    "nullable": true
                  },
                  "route_target_id": {
                    "type": "string",
                    "format": "uuid",
                    "nullable": true,
                    "description": "PA-137: the explicit Route Target of an ACCOUNT-level route. Double option: absent = keep the binding, `null` = clear it, a UUID = bind that Route Target (it must belong to this merchant, `404 route_target_not_found` otherwise). A PATCH that would leave BOTH `merchant_terminal_id` and `route_target_id` set is `422 invalid_request` — clear one of them in the same request."
                  },
                  "method_id": {
                    "type": "string",
                    "format": "uuid"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The updated route with its derived effective status."
          },
          "403": {
            "description": "Admin key required.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Route, terminal or method not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Incompatible binding / duplicate account-level route / archived terminal.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Invalid status/visibility or a category mismatch.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/webhook": {
      "post": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Register the webhook endpoint",
        "description": "Registers (or replaces) the HTTPS endpoint of the merchant backend that receives signed payment events. PA generates the HMAC signing secret server-side and returns it EXACTLY ONCE in this response — it is never surfaced again and never logged. Audited as `set_merchant_webhook` (details carry the URL only, never the secret).",
        "operationId": "setMerchantWebhook",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SetMerchantWebhookRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Webhook registered; `webhook_secret` is shown exactly once",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SetMerchantWebhookResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Invalid URL (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/stats": {
      "get": {
        "tags": [
          "Merchant Portal"
        ],
        "summary": "Merchant dashboard statistics",
        "description": "Dashboard aggregates of one merchant over a trailing window (`7d` / `30d`, default `7d`): Turnover EUR (with the previous-period delta), Approval Ratio, Transaction Count, Pay Ins, Credits/Refunds, Payment Option Distribution, the full payment-state histogram and the daily rollup (the Reconciliation view).\n\nSemantics: the **approved family** is `AUTHORIZED`, `CAPTURED`, `PARTIALLY_REFUNDED`, `REFUNDED` (refunds are approvals returned later); `turnover_eur` sums the `AUTHORIZED | CAPTURED` volume in MINOR units (cents — the same unit as every amount in this API) with currency EUR only — money IN, while refunded volume is reported as Credits/Refunds (`refunds_eur`, SUCCEEDED refunds from the `refunds` table); other currencies are reported per-currency in `turnover_by_currency` and are never mixed; `previous_turnover_eur` is the same aggregate over the PREVIOUS period of the same length (`[now-2N, now-N)`) — the delta basis of the Turnover card; `approval_ratio` is approved / (approved + FAILED) in percent (two decimals) — the apcopay formula `authorized / (authorized + declined + failed)`: `PENDING` and `UNKNOWN_PENDING_SYNC` are still in flight and stay out of the denominator; `payins` counts the approved payments (research §4.5) and the Deposits card carries its own EUR line (`deposits_eur`, `AUTHORIZED | CAPTURED` only — money confirmed IN, not yet refunded, with `previous_deposits_eur` as the delta basis); `payment_method_distribution` groups the window payments per `payment_method_type` (count only).\n\n`daily` groups by UTC calendar day and per currency; `by_state` is always the full state registry (zero-filled) so the portal renders a deterministic grid. Read-only aggregate over the existing tables — no new schema.\n\nAuth model (MVP): the same admin Bearer key as the operator surfaces — the merchant id comes from the path and is resolved strictly inside the authenticated tenant; a foreign or unknown merchant is a plain `404`.\n\nPA-49 G1: pass `from`+`to` (both, YYYY-MM-DD, inclusive) for a custom period — the response echoes `window: \"custom\"` and `window_days` as the inclusive day count.",
        "operationId": "getMerchantStats",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "window",
            "in": "query",
            "required": false,
            "description": "Trailing window of the aggregates. Ignored when `from`+`to` are given (PA-49: the custom range wins).",
            "schema": {
              "type": "string",
              "enum": [
                "7d",
                "30d"
              ],
              "default": "7d"
            }
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "PA-49 G1: custom range start (YYYY-MM-DD, inclusive, UTC). Requires `to`; `from < to`, span at most 90 days, else `400 invalid_request`.",
            "schema": {
              "type": "string",
              "format": "date"
            }
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "PA-49 G1: custom range end (YYYY-MM-DD, inclusive, UTC). Requires `from`.",
            "schema": {
              "type": "string",
              "format": "date"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Merchant statistics snapshot",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantStatsResponse"
                }
              }
            }
          },
          "400": {
            "description": "Unknown `window` value (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/payments": {
      "get": {
        "tags": [
          "Merchant Portal"
        ],
        "summary": "Merchant payments list",
        "description": "The Transactions grid of the merchant portal (apcopay-portal layout): the merchant's payments, newest first (`created_at DESC`, id as the deterministic tie-break), with an optional `status` filter and `limit`/`offset` pagination. `total` counts the payments matching the filter independently of the page.\n\nSummary projection with the apcopay columns: payment id, status, amount (minor units), currency, created_at, the latest attempt's provider + PSP reference, the payment option, the masked card metadata (PA-13 projection — brand + last4 + expiry, no PAN segments), the best-effort merchant context (`order_reference` from the request metadata, `email` from the request customer). No attempt journal — the full detail is the dedicated details read.\n\nSame admin Bearer (single-principal MVP); a foreign or unknown merchant is a plain `404`.",
        "operationId": "listMerchantPayments",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Optional payment-status filter (the canonical registry).",
            "schema": {
              "type": "string",
              "enum": [
                "PENDING",
                "AUTHORIZED",
                "CAPTURED",
                "PARTIALLY_REFUNDED",
                "REFUNDED",
                "FAILED",
                "UNKNOWN_PENDING_SYNC"
              ]
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size (clamped to 200).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 50,
              "maximum": 200
            }
          },
          {
            "name": "offset",
            "in": "query",
            "required": false,
            "description": "Page offset (0-based).",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            }
          },
          {
            "name": "q",
            "in": "query",
            "required": false,
            "description": "PA-49 G4: free-text search (contains match, ILIKE) over payment_id, PSP transaction reference, order_reference and email; at most 100 characters (else `400 invalid_request`). The `total` is search-scoped.",
            "schema": {
              "type": "string",
              "maxLength": 100
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Payments page",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantPaymentListResponse"
                }
              }
            }
          },
          "400": {
            "description": "Unknown `status` value or invalid pagination (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/payments/{payment_id}": {
      "get": {
        "tags": [
          "Merchant Portal"
        ],
        "summary": "Merchant payment details",
        "description": "The Transaction Details view of the merchant portal (apcopay-portal layout): the grid summary plus the PSP details (the attempt journal WITH the forensic provider facts — provider status / code / transaction reference, ADR-0002 §6.1; the collapse of the public `GET /v1/payments/{id}` summary does not bind this merchant-scoped read of the merchant's OWN data), the related refunds and the merchant's free-form request objects (`metadata`, `customer` — the expandable JSON of the details page). The Events timeline of the UI composes `attempts` (this response) with the webhook deliveries of `GET /v1/merchants/{id}/webhooks/deliveries?payment_id=…`.\n\nStrictly tenant+merchant scoped: a payment of another merchant (or an unknown id) is a plain `404`. Same admin Bearer.",
        "operationId": "getMerchantPaymentDetails",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "payment_id",
            "in": "path",
            "required": true,
            "description": "Payment id (`pay_…`).",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Payment details",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantPaymentDetailsResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Payment not found in this merchant (`payment_not_found` / `merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/payments/report.csv": {
      "get": {
        "tags": [
          "Merchant Portal"
        ],
        "summary": "Merchant transactions report (CSV)",
        "description": "The Transaction Report export: the same filter (`status`) as the payments list, delivered as a CSV attachment (`Content-Type: text/csv; charset=utf-8`, `Content-Disposition: attachment`). Columns: `payment_id`, `status`, `amount_minor`, `currency`, `capture_method`, `payment_method_type`, `provider`, `psp_reference`, `card_brand`, `card_last4`, `card_expiry`, `order_reference`, `email`, `created_at`, `updated_at` (RFC 3339 UTC timestamps, RFC 4180 quoting; the card columns carry the PA-13 masked projection only — never a PAN segment).\n\nPA-49 G2: `columns=` selects groups and/or individual columns (Choose Columns).\n\nPA-49 G5: the export is a STREAMING body walking keyset pages of 1000 rows (newest first) with a flat memory profile — the former bounded 10k snapshot is gone; any row count exports. A store error mid-stream aborts the body. Same admin Bearer; a foreign or unknown merchant is a plain `404`.",
        "operationId": "merchantPaymentsReportCsv",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Optional payment-status filter (the canonical registry).",
            "schema": {
              "type": "string",
              "enum": [
                "PENDING",
                "AUTHORIZED",
                "CAPTURED",
                "PARTIALLY_REFUNDED",
                "REFUNDED",
                "FAILED",
                "UNKNOWN_PENDING_SYNC"
              ]
            }
          },
          {
            "name": "columns",
            "in": "query",
            "required": false,
            "description": "PA-49 G2: comma-separated column keys and/or column-group keys (`transaction`, `bank`, `card`, `customer`). Columns: `payment_id`, `status`, `amount_minor`, `currency`, `capture_method`, `payment_method_type`, `provider`, `psp_reference`, `error_code`, `card_brand`, `card_last4`, `card_expiry`, `order_reference`, `email`, `created_at`, `updated_at`. Omitted → the full default set. The output order is always the canonical column order. Unknown keys / an empty selection → `400 invalid_request`.",
            "schema": {
              "type": "string",
              "example": "transaction,bank"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "CSV export",
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                },
                "example": "payment_id,status,amount_minor,currency,capture_method,payment_method_type,provider,psp_reference,card_brand,card_last4,card_expiry,order_reference,email,created_at,updated_at\npay_01900000-0000-7000-8000-00000000000a,AUTHORIZED,1050,EUR,automatic,card,payadmit,mock-txn,do_not_honor,VISA,4242,08/2028,order-77,player@example.com,2025-09-24T10:00:00Z,2025-09-24T10:00:05Z"
              }
            }
          },
          "400": {
            "description": "Unknown `status` value (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/webhooks/deliveries": {
      "get": {
        "tags": [
          "Merchant Portal"
        ],
        "summary": "Merchant webhook delivery journal (paginated, filterable)",
        "description": "The webhook delivery JOURNAL of the merchant (Admin v2 «Журнал доставок»): the deliveries of ALL payments and payouts of the merchant, newest first. Same projection discipline as `GET /v1/webhooks/deliveries` — the stored event payload (and with it every secret) is never projected into reads.\n\nPA-149: the read is PAGINATED (`limit` ≤ 200, default 25, `offset`) and FILTERABLE (`status`, `event_type`, `payment_id`, `since`/`until`); the filter-scoped `total` backs the «1–25 з N» counter of the console. Each row carries `target_url` for a MANUAL ONE-OFF re-send (masked: scheme+host+path, the query string is replaced by `?***` — it may carry a receiver secret) and `resend_of` (the delivery the row re-sends; absent for an original emission).\n\nDelivery is at-least-once (outbox worker, PA-40): `PENDING` rows are retried with backoff and dead-letter as `DEAD`; `DELIVERED` means the receiver acknowledged with a 2xx. The receiver verifies the `PA-Webhook-Signature` HMAC on its side — this log carries the PA-side delivery health (lifecycle state, attempt counter, last error class), not the receiver's verification result. Same admin Bearer; a foreign or unknown merchant is a plain `404`.",
        "operationId": "listMerchantWebhookDeliveries",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "payment_id",
            "in": "query",
            "required": false,
            "description": "Optional payment id (`pay_…`) to narrow the view to one payment's events.",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Delivery lifecycle state. Anything else is `400 invalid_request`.",
            "schema": {
              "type": "string",
              "enum": [
                "PENDING",
                "DELIVERED",
                "DEAD"
              ]
            }
          },
          {
            "name": "event_type",
            "in": "query",
            "required": false,
            "description": "The event type (`payment.authorized`, `payout.approved`, …) — exact match.",
            "schema": {
              "type": "string",
              "maxLength": 120
            }
          },
          {
            "name": "since",
            "in": "query",
            "required": false,
            "description": "Lower bound on `created_at` (inclusive), RFC 3339.",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "until",
            "in": "query",
            "required": false,
            "description": "Upper bound on `created_at` (exclusive), RFC 3339. Must be later than `since`.",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size (clamped to 200; the console default is 25).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 25,
              "maximum": 200
            }
          },
          {
            "name": "offset",
            "in": "query",
            "required": false,
            "description": "Rows to skip (0-based page offset).",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The delivery journal page (filter-scoped `total` included)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantWebhookDeliveryListResponse"
                }
              }
            }
          },
          "400": {
            "description": "Invalid filter or pagination — unknown `payment_id`/`status`, malformed `since`/`until`, `since` not earlier than `until`, non-positive `limit`, negative `offset` (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/webhooks/deliveries": {
      "get": {
        "tags": [
          "Webhooks"
        ],
        "summary": "Webhook delivery log of one payment or payout",
        "description": "Delivery history of the webhook outbox for one payment or one payout (PA-114): lifecycle status (`PENDING` / `DELIVERED` / `DEAD`), attempt counter, last error class and delivery time per event, oldest event first. Strictly tenant-scoped (a foreign payment/payout is a plain 404). Exactly one of `payment_id` / `payout_id` is required — both or neither is `invalid_request`. The stored event payload (and with it every secret) is never projected into reads.\n\nEvents are delivered asynchronously by the outbox worker: `payment.authorized`, `payment.captured`, `payment.refunded`, `payment.failed` and — PA-114 — `payout.approved`, `payout.completed`, `payout.declined`, `payout.cancelled`. Delivery is at-least-once; receivers dedup by `event_id` and verify `PA-Webhook-Signature: v1=<hex(HMAC-SHA256(raw_body, webhook_secret))>` over the raw delivered bytes.",
        "operationId": "listWebhookDeliveries",
        "parameters": [
          {
            "name": "payment_id",
            "in": "query",
            "required": false,
            "description": "Payment id (`pay_…`) whose delivery log is requested. Mutually exclusive with `payout_id` — exactly one of the two is required.",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "payout_id",
            "in": "query",
            "required": false,
            "description": "Payout id (`po_…`) whose delivery log is requested (PA-114). Mutually exclusive with `payment_id` — exactly one of the two is required.",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Delivery history",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookDeliveryListResponse"
                }
              }
            }
          },
          "400": {
            "description": "Exactly zero or both of `payment_id` / `payout_id` supplied (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Payment or payout not found in this tenant (`payment_not_found` / `payout_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/audit": {
      "get": {
        "tags": [
          "Audit"
        ],
        "summary": "Audit trail read",
        "description": "The immutable audit trail, newest first (`created_at DESC, id DESC`). Every filter combines conjunctively; paginate with the `next_before_id` cursor (`before_id`) or an `offset`. Returns `{events, count, total, next_before_id}` (the PA-25 `events`/`count` fields are unchanged).",
        "operationId": "listAudit",
        "parameters": [
          {
            "name": "q",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "Free-text over actor/action/entity/details."
          },
          {
            "name": "actor",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "entity_type",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "entity_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "merchant_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "psp_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "action",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "maximum": 500
            },
            "description": "Default 100, max 500."
          },
          {
            "name": "before_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "format": "int64"
            },
            "description": "Keyset cursor (exclusive)."
          },
          {
            "name": "offset",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 0
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The audit page (`events`, `count`, `total`, `next_before_id`)."
          },
          "400": {
            "description": "Invalid action, timestamp, limit, offset or cursor.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/tenants/{id}/rotate-key": {
      "post": {
        "tags": [
          "Tenant Keys"
        ],
        "summary": "Rotate the tenant API key",
        "description": "Generates a new tenant API key: it is valid IMMEDIATELY, the replaced key stays working for a 24h grace period (`old_key_expires_at`), then expires. The raw `new_key` is returned EXACTLY ONCE and is never stored (only its SHA-256 hash is). Keys are issued per tenant — the authenticated key must belong to the tenant named in the path.",
        "operationId": "rotateTenantKey",
        "parameters": [
          {
            "$ref": "#/components/parameters/TenantId"
          }
        ],
        "responses": {
          "200": {
            "description": "New key issued; the old key enters the grace period",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RotateKeyResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Tenant not found (`tenant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/tenants/{id}/keys/{key_id}": {
      "delete": {
        "tags": [
          "Tenant Keys"
        ],
        "summary": "Revoke a tenant API key",
        "description": "Immediate revocation: the key answers `401` starting from the next request (no grace). Revoking the key you are currently authenticated with locks out the caller — rotate first, then revoke the old `key_id`.",
        "operationId": "revokeTenantKey",
        "parameters": [
          {
            "$ref": "#/components/parameters/TenantId"
          },
          {
            "name": "key_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Key id of the key to revoke (`key_…`)."
          }
        ],
        "responses": {
          "204": {
            "description": "Key revoked"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Tenant or key not found (`tenant_not_found` / `key_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/tenants/{id}/payouts-enabled": {
      "put": {
        "tags": [
          "Tenant Keys"
        ],
        "summary": "Toggle the tenant payouts domain gate (PA-97)",
        "description": "The OPERATOR toggle of the TENANT-level payouts domain gate (`tenants.payouts_enabled`, fail-closed default false). ADMIN-ONLY: a merchant-scoped key answers `403 forbidden`; the authenticated tenant must be the tenant named in the path (a foreign id is a plain `404`). The change and its `tenant.payouts_enabled` audit event (enabled value + free-text `reason` verbatim) are committed in one transaction.\n\nSemantics (PA-97, fail-closed by both gates): the operator payout surface (`GET /v1/payouts` + approve/decline) passes when this gate is ON; the merchant-scoped payout surface (`POST /v1/merchants/{id}/payouts`) requires this gate AND the per-merchant `payouts_enabled` toggle.",
        "operationId": "setTenantPayoutsEnabled",
        "parameters": [
          {
            "$ref": "#/components/parameters/TenantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SetTenantPayoutsEnabledRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The settled gate state.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SetTenantPayoutsEnabledResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`) — the tenant payouts gate is an operator surface.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Tenant not found (`tenant_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/route-targets/{rt_id}/status": {
      "patch": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Change route target status",
        "description": "Lifecycle transition of one Route Target (PA-58, PA-55 §8): ENABLED / DRAINING / DEGRADED / DISABLED. Legal manual transitions follow the soft-disable flow — ENABLED ↔ DRAINING ↔ DISABLED with the return paths DISABLED → ENABLED or through DRAINING; same-state requests are `409 invalid_state_transition`. DEGRADED is set by the system only (limit machinery, ADR-0004 §4.5): an admin request to set it is rejected; the manual surface may reset a degraded target (`DEGRADED → ENABLED`) or take it further out (→ DRAINING/DISABLED). DRAINING and DISABLED exclude NEW payments from routing (422 `no_eligible_route` when nothing else remains) while in-flight attempts keep resolving (sync/refund/webhooks). Audited as `route_target.status_change` with before/after states.",
        "operationId": "changeRouteTargetStatus",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "rt_id",
            "in": "path",
            "required": true,
            "description": "Route target identifier (`rt_...`).",
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RouteTargetStatusChangeRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Lifecycle status changed",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RouteTargetStatusChangeResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant or route target not found in this tenant (`merchant_not_found`, `route_target_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Lifecycle transition not allowed (`invalid_state_transition`) — matrix violation or a concurrent status change",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/route-targets/{rt_id}/test-mode": {
      "put": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Change the Apcopay live/test mode of a route target",
        "description": "PA-123/PA-124: switches ONE Apcopay Route Target between TEST and LIVE mode. The flag is owned by PA (`route_targets.capabilities.is_test`) and published into the fork MCA `metadata` with a READ-MERGE-WRITE (PA-124): PA reads the current MCA metadata (`GET .../connectors/{mca}`) and overlays the PA-owned keys `{\"is_test\": <value>, ...provider_routing}` (`force_bank`, `force_payment`, `main_acquirer`, `force_mid`, `payment_method_data`), so keys PA does not model (`use_hpp` on HPP targets, future keys) survive — the fork REPLACES `metadata` wholesale. A failed read is fail-closed (`502 fork_admin_unreachable`): PA never publishes blindly. `502 fork_admin_rejected` means the fork refused the metadata WRITE. Only apcopay Route Targets carry the flag: another connector is `422 test_mode_unsupported_provider`, a provider account without a fork MCA reference is `409 test_mode_mca_ref_missing`, an unconfigured fork proxy is `503 fork_proxy_not_configured` (fail-closed: nothing changes). SHARED MCA (PA-124): `is_test` is a property of the MCA, while PA stores it per Route Target — a sibling of the TENANT declaring the opposite value answers `409 test_mode_shared_mca_conflict` with the ids in `details.route_target_ids` and nothing changes; a legacy sibling without the flag does not block (the flip is its first declaration). `force=true` (tenant/admin key only, `403` for a merchant-scoped key) aligns every such sibling in the SAME transaction as the target and returns `shared_route_target_ids`. A repeat of the stored value is idempotent (`200`, `published: false`, no fork call, no audit event). Audited as `route_target.test_mode_changed` with before/after in the details, in the SAME transaction as the `capabilities.is_test` write.",
        "operationId": "changeRouteTargetTestMode",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "rt_id",
            "in": "path",
            "required": true,
            "description": "Route target identifier (`rt_...`).",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "force",
            "in": "query",
            "required": false,
            "description": "PA-124: align the `capabilities.is_test` of every Route Target of the tenant sharing the same fork MCA, in the SAME transaction as the target (instead of `409 test_mode_shared_mca_conflict`). Tenant/admin key only.",
            "schema": {
              "type": "boolean",
              "default": false
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RouteTargetTestModeRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Live/test mode changed (or already the requested value — `published: false`)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RouteTargetTestModeResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "`forbidden` — `force=true` requires the tenant (admin) key; a merchant-scoped key cannot change the mode of a shared MCA for other route targets",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Merchant or route target not found in this tenant (`merchant_not_found`, `route_target_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`test_mode_mca_ref_missing` — the provider account has no fork MCA reference; `test_mode_shared_mca_conflict` — a route target of the tenant sharing this fork MCA declares the opposite mode (ids in `details.route_target_ids`; nothing changed; use `force=true` to align); `route_target_capabilities_changed` — a concurrent routing edit won, re-read and retry",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "`test_mode_unsupported_provider` — the target is not an apcopay one; `invalid_request` — malformed body",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "502": {
            "description": "`fork_admin_unreachable` — the fork admin API is unreachable OR the current MCA metadata could not be read (read-merge-write fails closed: no blind publish); `fork_admin_rejected` — the fork refused the metadata write. The route target is UNCHANGED in both cases.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "503": {
            "description": "`fork_proxy_not_configured` — the deployment has no fork admin wiring (`PA_HS_FORK_*`); nothing changed",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/payment-methods": {
      "get": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "List the payment methods of a merchant (PA-133)",
        "description": "The operator read of the merchant's per-method routing config (`route_target_methods`): every configured method across its Route Targets, with its currency/country/amount scope, cascade priority and enable toggle. ADMIN-ONLY (a merchant-scoped key answers `403 forbidden` — this is operator routing config). A foreign or unknown merchant is a plain `404`.",
        "operationId": "listMerchantPaymentMethods",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "200": {
            "description": "The merchant's payment methods (any type).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "merchant_id": {
                      "type": "string",
                      "example": "mer_01900000-0000-7000-8000-000000000001"
                    },
                    "methods": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "route_target_id": {
                            "type": "string"
                          },
                          "method_type": {
                            "type": "string",
                            "enum": [
                              "card",
                              "apple_pay",
                              "google_pay",
                              "open_banking"
                            ]
                          },
                          "currencies": {
                            "type": "array",
                            "items": {
                              "type": "string"
                            }
                          },
                          "countries": {
                            "type": "array",
                            "items": {
                              "type": "string"
                            }
                          },
                          "min_amount": {
                            "type": "integer"
                          },
                          "max_amount": {
                            "type": "integer"
                          },
                          "priority": {
                            "type": "integer"
                          },
                          "enabled": {
                            "type": "boolean"
                          }
                        },
                        "required": [
                          "route_target_id",
                          "method_type",
                          "currencies",
                          "countries",
                          "priority",
                          "enabled"
                        ]
                      }
                    }
                  },
                  "required": [
                    "merchant_id",
                    "methods"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/route-targets/{rt_id}/payment-methods/{method_type}": {
      "put": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Add or update a payment method of a route target (PA-133)",
        "description": "The operator add/edit of one payment method of a Route Target (`route_target_methods`, upsert). The method carries its OWN currency/country/amount scope (empty `currencies`/`countries` = any), its cascade priority (lower = higher; the Route Target priority/weight/id break ties) and its enable toggle (a disabled method never routes; the target stays reachable for its other methods). `method_type` is the normalized word: `card` (the umbrella of raw-card, saved-instrument and hosted-page forms), `apple_pay`, `google_pay`, `open_banking`. ADMIN-ONLY (a merchant-scoped key answers `403 forbidden`). Error split: an unknown `method_type` or `min_amount > max_amount` is `422 invalid_request`; a foreign route target is `404`.",
        "operationId": "upsertMerchantPaymentMethod",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "rt_id",
            "in": "path",
            "required": true,
            "description": "Route target identifier (`rt_...`).",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "method_type",
            "in": "path",
            "required": true,
            "description": "The normalized payment method type (`card` / `apple_pay` / `google_pay` / `open_banking`).",
            "schema": {
              "type": "string",
              "enum": [
                "card",
                "apple_pay",
                "google_pay",
                "open_banking"
              ]
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "currencies": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    },
                    "description": "ISO 4217 codes this method may process; empty = any currency."
                  },
                  "countries": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    },
                    "description": "ISO 3166-1 alpha-2 billing countries this method may serve; empty = any country."
                  },
                  "min_amount": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Lower amount bound in minor units (inclusive); absent/null = no lower bound."
                  },
                  "max_amount": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Upper amount bound in minor units (inclusive); absent/null = no upper bound."
                  },
                  "priority": {
                    "type": "integer",
                    "description": "Cascade priority among methods of the same type; lower = higher priority."
                  },
                  "enabled": {
                    "type": "boolean",
                    "description": "Enable/disable toggle (default true)."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The settled payment method.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "route_target_id": {
                      "type": "string"
                    },
                    "method_type": {
                      "type": "string"
                    },
                    "currencies": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    },
                    "countries": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    },
                    "min_amount": {
                      "type": "integer"
                    },
                    "max_amount": {
                      "type": "integer"
                    },
                    "priority": {
                      "type": "integer"
                    },
                    "enabled": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "route_target_id",
                    "method_type",
                    "currencies",
                    "countries",
                    "priority",
                    "enabled"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Merchant or route target not found in this tenant (`merchant_not_found`, `route_target_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Unknown `method_type`, non-ISO currency/country codes, negative bounds or `min_amount > max_amount` (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      },
      "delete": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Remove a payment method of a route target (PA-133)",
        "description": "The operator removal of one payment method of a Route Target. Removing the LAST method of a type makes that type unroutable on the target (an empty cascade for the type answers `422 no_eligible_route`). ADMIN-ONLY (a merchant-scoped key answers `403 forbidden`). An unknown `method_type` is `422 invalid_request`; a foreign route target is `404`; a method not configured on the target is `404 payment_method_not_found`.",
        "operationId": "deleteMerchantPaymentMethod",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "rt_id",
            "in": "path",
            "required": true,
            "description": "Route target identifier (`rt_...`).",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "method_type",
            "in": "path",
            "required": true,
            "description": "The normalized payment method type (`card` / `apple_pay` / `google_pay` / `open_banking`).",
            "schema": {
              "type": "string",
              "enum": [
                "card",
                "apple_pay",
                "google_pay",
                "open_banking"
              ]
            }
          }
        ],
        "responses": {
          "204": {
            "description": "The payment method was removed."
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Merchant or route target not found in this tenant (`merchant_not_found`, `route_target_not_found`) or the method is not configured on the target (`payment_method_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Unknown `method_type` (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/rotate-webhook-secret": {
      "post": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Rotate the webhook signing secret",
        "description": "Replaces the HMAC signing secret of the registered webhook endpoint (PA-34). The NEW secret is generated server-side and returned EXACTLY ONCE in this response — deliveries are signed with it immediately, while the replaced secret stays verifiable receiver-side until `old_secret_expires_at` (`PA_WEBHOOK_SECRET_GRACE_DAYS`, default 7 days): verify BOTH secrets during the grace window (dual-verify). Audited as `rotate_webhook_secret` (details carry the URL and the rotation time, never a secret).",
        "operationId": "rotateMerchantWebhookSecret",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "201": {
            "description": "Secret rotated; `webhook_secret` is the NEW active secret, shown exactly once",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RotateWebhookSecretResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Merchant has no webhook endpoint registered (`webhook_not_registered`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/selfprofile": {
      "get": {
        "tags": [
          "Merchant Portal"
        ],
        "summary": "Self-service profile of the merchant",
        "description": "One tenant-scoped read with everything the handover promised (PA-66, the `/portal` Profile tab): the access triple — `api_key` (the SAME bearer of THIS request echoed back: in the single-principal MVP the tenant API key IS the admin key the merchant already holds), `merchant_id` and the production/sandbox base URLs — plus the webhook configuration and the routing data. `webhook_url` is the registered endpoint (`null` when none); `webhook_secret_status` is `issued` (a webhook is registered — the secret was shown exactly once at registration/last rotation and is NEVER returned again; the only path to a new secret value is the PA-34 rotation) or `never_shown` (no webhook registered). `providers` lists the linked PSPs (connector + MID, currency scope, connector lifecycle status) and `test_cards` carries the documented sandbox terminal fixtures. Audited as `selfprofile.read` with masked details (merchant id only).",
        "operationId": "getMerchantSelfProfile",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "200": {
            "description": "Self-service profile of the merchant (`api_key` = the bearer of this request)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantSelfProfileResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/webhook-url": {
      "patch": {
        "tags": [
          "Merchant Portal"
        ],
        "summary": "Retarget the webhook endpoint (self-service)",
        "description": "Changes the registered webhook endpoint URL WITHOUT rotating the signing secret (PA-66 self-service): the active secret and the PA-34 grace slot stay byte-identical, so the receiver keeps verifying with the key it already holds. HTTPS-only validation — plain http, garbage or overlong values are rejected; requires an EXISTING webhook registration (URL and secret are a pair). Audited as `merchant.update_webhook_url` (details carry the new URL, never a secret).",
        "operationId": "updateMerchantWebhookUrl",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateWebhookUrlRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Endpoint retargeted; the signing secret is unchanged",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UpdateWebhookUrlResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Merchant has no webhook endpoint registered (`webhook_not_registered`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Invalid URL — not https, garbage or over 2048 characters (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/ops/reconciliation-health": {
      "get": {
        "tags": [
          "Ops"
        ],
        "summary": "Tenant reconciliation health (admin console, PA-69)",
        "description": "The tenant-wide current-state reconciliation snapshot (PA-69; research §3.5/§5): the PA-46 dispatch-journal unresolved count with the oldest unresolved dispatch (compare against `sync_recovery_stale_secs` — `PA_SYNC_RECOVERY_STALE_SECS`), the stuck-checkout candidates (the PA-36 predicate, threshold `PA_RECONCILE_AFTER_MINS`), the `UNKNOWN_PENDING_SYNC` backlog and the webhook-outbox health. No window — monitoring asks what is stuck NOW; the per-merchant windowed counterpart is `GET /v1/merchants/{id}/stats`. Read-only: no audit rows.",
        "operationId": "getOpsReconciliationHealth",
        "responses": {
          "200": {
            "description": "The tenant-wide reconciliation snapshot",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReconciliationHealthResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/ops/outbox/dead": {
      "get": {
        "tags": [
          "Ops"
        ],
        "summary": "List webhook dead letters (admin console, PA-69)",
        "description": "The PA-40 outbox dead-letter page of the tenant (PA-69; research §3.5/§5): the most recent DEAD deliveries (newest first) with the delivery facts (attempt counter, last error class — the stored event payload is never projected) plus the honest total backlog count. Delivery is at-least-once; receivers verify the HMAC signature on their side — this log is the PA-side delivery health. Read-only: no audit rows.",
        "operationId": "getOpsOutboxDead",
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size of the letters list (clamped to 200).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 50,
              "maximum": 200
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The dead-letter page plus the total backlog count",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OutboxDeadResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/ops/rate-limit": {
      "get": {
        "tags": [
          "Ops"
        ],
        "summary": "Rate-limit snapshot (admin console, PA-69)",
        "description": "The PA-47 read-only rate-limit snapshot (PA-69; research §3.5/§5): which backend is active (`memory`/`redis`), the sliding-window length, the default and per-endpoint limits, the unauthenticated per-IP limit and — for the memory backend — the live per-endpoint usage of the CALLING tenant plus the process-level tracked-bucket counters. The Redis backend holds the shared buckets in Redis; the snapshot reports the configuration only (`tenant_buckets`/`tracked` are absent — honest MVP gap, research §7 open question 4). Read-only, no secrets.",
        "operationId": "getOpsRateLimit",
        "responses": {
          "200": {
            "description": "The rate-limit configuration and (memory backend) live tenant usage",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RateLimitSnapshotResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/psp/me": {
      "get": {
        "tags": [
          "PSP Portal"
        ],
        "summary": "PSP profile (scope identity, capabilities, fixtures)",
        "description": "The scope identity of the authenticated PSP key: the connector code (resolved FROM the key — the scope is not an input), the display name and the PA-59 execution snapshot of the connector rows, the EFFECTIVE capability snapshot (the last PSP anкета confirmation over the static PA-53 default snapshot), the production/sandbox base URLs and the sandbox test-card fixtures of the connector. Works for a PSP without provider rows yet (honest empty state).",
        "operationId": "getPspProfile",
        "responses": {
          "200": {
            "description": "PSP profile",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspProfileResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ]
      }
    },
    "/v1/psp/me/mcas": {
      "get": {
        "tags": [
          "PSP Portal"
        ],
        "summary": "The PSP's own connections (merchant × MID × MCA)",
        "description": "Every connection of the PSP across ALL merchants: providers of the connector code joined to the merchants and the provider accounts (the fork MCA reference), with the link scope (currencies/countries), the PA-59 execution snapshot and the PA-58 Route Target lifecycle statuses of every MID. No credentials (the MCA reference is a proxy address), no route priorities/weights (operator data), no other PSPs.",
        "operationId": "listPspMcas",
        "responses": {
          "200": {
            "description": "The PSP's own connections",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspMcaListResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ]
      }
    },
    "/v1/psp/me/dispatch": {
      "get": {
        "tags": [
          "PSP Portal"
        ],
        "summary": "The PSP's own dispatches (attempts routed to the connector)",
        "description": "The PSP's own attempts (`attempts.provider_connector_code` = the key's scope), newest first, joined to the payment: PA state, amount/currency (minor units, never mixed), the PSP's own reference (`provider_transaction_id` — the pspid of the Apcopay model), the verbatim provider status/code, the final PA error code, merchant and MID. The PSP sees its ATTEMPTS — never the payment route as a whole (no competing PSPs). No customer PII.",
        "operationId": "listPspDispatches",
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "description": "Page size (clamped to 200)."
          },
          {
            "name": "offset",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            },
            "description": "Page offset."
          }
        ],
        "responses": {
          "200": {
            "description": "The dispatch grid",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspDispatchListResponse"
                }
              }
            }
          },
          "400": {
            "description": "`invalid_request` — non-positive limit / negative offset",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ]
      }
    },
    "/v1/psp/me/health": {
      "get": {
        "tags": [
          "PSP Portal"
        ],
        "summary": "Health block of the PSP",
        "description": "Windowed health over the PSP's own dispatches: attempt-status counts (zero-filled registry + success rate over DECIDED attempts — in-flight and UNKNOWN stay out of the denominator; an undecided window is `null`, never 0%), the unresolved PA-46 dispatch-journal entries (in-flight or crashed dispatches — the money may be on the PSP without a recorded outcome), the decline breakdown by VERBATIM bank codes and the daily (UTC-day × currency) rollup of the dispatch volume.",
        "operationId": "getPspHealth",
        "parameters": [
          {
            "name": "window",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "7d",
                "30d"
              ],
              "default": "7d"
            },
            "description": "Aggregation window."
          }
        ],
        "responses": {
          "200": {
            "description": "Health block",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspHealthResponse"
                }
              }
            }
          },
          "400": {
            "description": "`invalid_request` — unknown window",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ]
      }
    },
    "/v1/psp/me/capabilities": {
      "get": {
        "tags": [
          "PSP Portal"
        ],
        "summary": "The effective capability snapshot",
        "description": "The PA-53 capability snapshot of the PSP: the LAST `psp.capabilities_confirmed` audit event (the PSP's own anкета confirmation, evidence `CONFIRMED_BY_PSP`) over the static PA-53 default snapshot (research facts; read-only baseline). `source` states which one is returned; a malformed stored snapshot falls back to the default (never fabricate flags).",
        "operationId": "getPspCapabilities",
        "responses": {
          "200": {
            "description": "Effective capability snapshot",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspCapabilitiesView"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ]
      },
      "put": {
        "tags": [
          "PSP Portal"
        ],
        "summary": "Confirm the capability anкeta (PA-53)",
        "description": "The PSP confirms its capability flags (all six REQUIRED — a partial anкета would silently erase the rest of the snapshot). The flags are non-secret and land as the append-only audit event `psp.capabilities_confirmed` (actor `psp:<connector_code>`, entity `connector`, evidence `CONFIRMED_BY_PSP`) — the LAST confirmation is the durable value read back by GET (a dedicated configs/kv store is the PA-24 extension). PA-70 stores no migration; the append-only audit trail (PA-25) is the storage.",
        "operationId": "putPspCapabilities",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PspCapabilitiesPutRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The confirmed snapshot",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspCapabilitiesView"
                }
              }
            }
          },
          "400": {
            "description": "`invalid_request` — malformed body",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ]
      }
    },
    "/v1/psp/me/mca/{mca_id}/credentials": {
      "patch": {
        "tags": [
          "PSP Portal"
        ],
        "summary": "Rotate the MCA credentials (fork admin API proxy)",
        "description": "The PSP rotates the credentials of one of ITS MCAs. The MCA reference is resolved strictly inside the connector scope (a foreign MCA is 404). The values (the COMPLETE SignatureKey set — the fork's `MerchantConnectorUpdate.connector_account_details` REPLACES the whole credential object, so partial rotations are rejected with 422 to avoid clearing omitted fields) are STREAMED to the fork admin API (`POST /account/{merchant}/connectors/{mca}`) and NEVER persisted in PA — not in the Store, not in the audit trail, not in logs. The audit event `psp.credentials_rotated` carries the rotated FIELD NAMES only. Error mapping: fork rejection → `502 fork_admin_rejected` (status number only, the fork body is never passed through), fork unreachable → `502 fork_admin_unreachable`, proxy not configured → `503 psp_proxy_not_configured`.",
        "operationId": "rotatePspMcaCredentials",
        "parameters": [
          {
            "name": "mca_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "maxLength": 128
            },
            "description": "The fork MCA reference (`provider_accounts.external_mca_ref`, e.g. `mca_…`). Resolved strictly inside the PSP connector scope — a foreign MCA is 404."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PspCredentialsRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "What was rotated (field NAMES only)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PspCredentialsRotatedResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "`mca_not_found` — the MCA reference is outside the connector scope (foreign PSP)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "`invalid_request` — partial/empty/overlong credential set",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "502": {
            "description": "`fork_admin_rejected` | `fork_admin_unreachable`",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "503": {
            "description": "`psp_proxy_not_configured`",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ]
      }
    },
    "/psp": {
      "get": {
        "tags": [
          "PSP Portal"
        ],
        "summary": "PSP portal console",
        "description": "PA-70: the processor's self-service console at `/psp` — a static, same-origin SPA served by the API itself (the PA-52 `/admin` and PA-65 `/portal` pattern: embedded at compile time, no filesystem lookup). The surface is UNAUTHENTICATED on the serving side: it carries no PSP data of its own — every API call the SPA makes goes to the authenticated `/v1/psp/*` routes with the PSP Bearer typed into the login box (kept in sessionStorage); the key IS the connector scope. A strict CSP (same-origin scripts/styles/connect only, no framing) is delivered by the HTML itself plus hardening headers.",
        "operationId": "pspPortalConsole",
        "security": [],
        "responses": {
          "200": {
            "description": "PSP portal console page",
            "content": {
              "text/html": {
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    },
    "/psp/static/{asset}": {
      "get": {
        "tags": [
          "PSP Portal"
        ],
        "summary": "PSP portal static assets",
        "description": "PA-70: the static assets of the `/psp` console (psp.css, psp.js). The allowlist is closed — anything else is a plain 404 (no path traversal surface, no directory listing).",
        "operationId": "pspPortalStaticAsset",
        "security": [],
        "parameters": [
          {
            "name": "asset",
            "in": "path",
            "required": true,
            "description": "Static asset file name of the PSP console.",
            "schema": {
              "type": "string",
              "enum": [
                "psp.css",
                "psp.js"
              ]
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Static asset",
            "content": {
              "text/css": {
                "schema": {
                  "type": "string"
                }
              },
              "application/javascript": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "Unknown asset (closed allowlist)"
          }
        }
      }
    },
    "/v1/sdk/capture": {
      "post": {
        "tags": [
          "SDK Capture"
        ],
        "summary": "Browser card capture — tokenize PAN/CVV into a single-use vault token (PA-48)",
        "description": "The real Locker capture surface of the PA Secure Fields SDK: the sandboxed SDK iframe posts PAN/CVV DIRECTLY here and receives a single-use vault token. PA forwards the card bundle to the configured capture client (fork Locker proxy) and holds the values only in flight — nothing card-shaped is logged, persisted or echoed.\n\nAuth: the PUBLIC publishable key (`X-Publishable-Key: pk_...`, body `publishable_key` fallback) — derived per merchant at onboarding, re-displayed by the merchant APIs. It binds the capture to a merchant but carries no bearer power.\n\nLoad control: hard per-key sliding window (`PA_SDK_CAPTURE_RPM`, default 30/min) + per-IP window; over-limit answers `429 rate_limited` + `Retry-After` before any card data is processed. Origin allowlist (`PA_SDK_CAPTURE_ALLOWED_ORIGINS`) applies when configured. No Idempotency-Key: every call mints a FRESH vault token (each token is consumed exactly once by the instrument registration).",
        "operationId": "sdkCapture",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SdkCaptureRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Card tokenized. Response headers carry `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer` and a restrictive CSP — token material is never cacheable.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SdkCaptureResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "description": "Missing/unknown publishable key (`invalid_publishable_key`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "403": {
            "description": "Request origin not on the configured allowlist (`origin_not_allowed`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure (`invalid_request`) or the capture surface rejected the card (`capture_rejected`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "description": "Per-key or per-IP capture rate limit exceeded (`rate_limited`)",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "502": {
            "description": "Capture surface unreachable/unavailable (`capture_unavailable`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "options": {
        "tags": [
          "SDK Capture"
        ],
        "summary": "CORS preflight of the capture endpoint",
        "description": "Never authenticated (browsers send no custom headers on preflights). Answers `204` with `Access-Control-Allow-*` headers when the Origin is acceptable (wildcard posture when no allowlist is configured), `403 origin_not_allowed` otherwise.",
        "operationId": "sdkCapturePreflight",
        "security": [],
        "responses": {
          "204": {
            "description": "Preflight accepted (no body)"
          },
          "403": {
            "description": "Origin not allowed (`origin_not_allowed`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/api-key": {
      "post": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Issue a merchant-scoped API key (PA-72)",
        "description": "Generates the merchant's OWN Bearer key and returns the raw value EXACTLY ONCE (PA-24 once-semantics); only the SHA-256 hash is stored (`merchants.api_key_hash`, migration 0019). Tenant isolation: from now on the casino uses THIS key on the `/portal` and the `/v1/merchants/{own_id}/*` surface — it can read and rotate ONLY its own merchant (a foreign id is `404 merchant_not_found`), cannot list `/v1/merchants` and cannot reach `/v1/ops/*` (both `403 forbidden`). The legacy tenant key keeps working as the admin principal (operator + PlayPulse compatibility) until every casino holds its own key. Issuing a key again REPLACES the current hash (the old key dies immediately) and is audited `merchant.api_key_issued` (hashes only, never raw values). Admin Bearer only.",
        "operationId": "issueMerchantApiKey",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "201": {
            "description": "Key issued; `api_key` is the raw key, shown exactly once",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IssueMerchantKeyResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`) — PA-72 tenant isolation.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/api-key/rotate": {
      "post": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Rotate the merchant-scoped API key (PA-72)",
        "description": "Generates a NEW merchant-scoped key, returns it EXACTLY ONCE and keeps the replaced key verifiable until `old_key_expires_at` (24h grace, the PA-24 window). The merchant's own scoped key may rotate ITSELF; the admin key may rotate any tenant merchant; a merchant-scoped key on a foreign merchant is a plain `404`. Audited `merchant.api_key_rotated` (hashes + grace expiry only).",
        "operationId": "rotateMerchantApiKey",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "201": {
            "description": "Key rotated; `api_key` is the NEW raw key (shown once); the old key works until `old_key_expires_at`",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IssueMerchantKeyResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/portal/docs/{doc}": {
      "get": {
        "tags": [
          "Admin"
        ],
        "summary": "Merchant documentation (markdown, this origin)",
        "description": "PA-72 follow-up (casino feedback #3): the merchant-facing documentation served from THIS origin — the reviewed docs only, never the GitLab. Allowlist: handover-package.md, casino-onboarding-checklist.md, pa-payments-api.md, pa-secure-fields.md, sdk-readme.md. PA-74: the same documents render INSIDE the `/docs` Redocly reference (sidebar «Guides» group) — this endpoint stays as the raw-markdown compatibility surface and is no longer linked from the portal UI.",
        "operationId": "merchantPortalStaticAsset",
        "security": [],
        "parameters": [
          {
            "name": "asset",
            "in": "path",
            "required": true,
            "description": "Static asset file name of the portal console.",
            "schema": {
              "type": "string",
              "enum": [
                "portal.css",
                "portal.js"
              ]
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Static asset",
            "content": {
              "text/css": {
                "schema": {
                  "type": "string"
                }
              },
              "application/javascript": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "Unknown asset (closed allowlist)"
          }
        }
      }
    },
    "/docs/swagger-ui": {
      "get": {
        "tags": [
          "Docs"
        ],
        "summary": "Try-it-out console (Swagger UI)",
        "description": "Serves the Swagger UI console bound to `GET /docs/openapi.json` — the interactive counterpart of the `GET /docs` reference page (authorize with the tenant Bearer key, execute requests against this origin). Unauthenticated.",
        "security": [],
        "operationId": "getDocsSwaggerUi",
        "responses": {
          "200": {
            "description": "Swagger UI HTML page",
            "content": {
              "text/html": {
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    },
    "/": {
      "get": {
        "tags": [
          "Docs"
        ],
        "summary": "Landing redirect to the API reference",
        "description": "Redirects (302) to `/docs` — the branded API reference and integration guides. Lets the bare API base URL (sandbox or production) serve as the documentation entry point for integration engineers.",
        "security": [],
        "operationId": "rootRedirect",
        "responses": {
          "302": {
            "description": "Redirect to `/docs`",
            "headers": {
              "Location": {
                "description": "The reference page URL (`/docs`)",
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/h2h": {
      "put": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Toggle the per-merchant H2H (S2S raw card) gate (PA-78)",
        "description": "ADR-0005 §3.5: the OPERATOR toggle of the per-merchant H2H (S2S raw card) gate. ADMIN-ONLY: a merchant-scoped key answers `403 forbidden`. The contractual condition of enabling is the merchant's current PCI DSS AoC (Attestation of Compliance) — the fact is recorded by the `merchant.h2h_enabled` audit event with the free-text `reason` and the `aoc_reference` verbatim (PA does not validate the AoC — the human gate stays with the operator). The change and its audit event are committed in one transaction. The gate is one of TWO levels: the deployment kill-switch `PA_H2H_ENABLED` must also be true. Disabling is the instant rollback (ADR-0005 §6). A foreign or unknown merchant is a plain `404`.",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "enabled"
                ],
                "properties": {
                  "enabled": {
                    "type": "boolean",
                    "description": "Target gate state (`true` = raw-card payments accepted for this merchant — still subject to `PA_H2H_ENABLED`)."
                  },
                  "reason": {
                    "type": "string",
                    "description": "Free-text operator reason, recorded in the audit event verbatim."
                  },
                  "aoc_reference": {
                    "type": "string",
                    "description": "Reference of the merchant's PCI DSS AoC (number/date of the QSA report or self-assessment) — recorded verbatim; the contractual condition of enabling."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The settled gate state.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "merchant_id": {
                      "type": "string",
                      "example": "mer_01900000-0000-7000-8000-000000000001"
                    },
                    "h2h_enabled": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "merchant_id",
                    "h2h_enabled"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`) — the H2H gate is an operator surface (ADR-0005 §3.5).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Malformed body: missing `enabled` (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        },
        "operationId": "setMerchantH2h"
      }
    },
    "/v1/merchants/{id}/std-min-deposits": {
      "put": {
        "tags": [
          "Merchant Onboarding"
        ],
        "operationId": "setMerchantStdMinDeposits",
        "summary": "Set the contractual STD deposit threshold (PA-127)",
        "description": "The OPERATOR update of `merchants.std_min_deposits` — the contract term that decides how many SUCCESSFUL customer deposits (states `AUTHORIZED`/`CAPTURED`/`PARTIALLY_REFUNDED`/`REFUNDED`) a payer needs before the payment is STD (redep) traffic and may use the STD terminal (and the wallets, which are STD-only). The default is 1 — exactly the PA-126 rule (first deposit `ftd`, second `redep`), so an unconfigured merchant keeps the old behavior. Resolving the stream is a bounded indexed count over `payments (merchant_id, customer_reference, status)` (migrations 0034/0035), and the decision is PROVEN on every attempt by the persisted evidence (`deposit_stream_prior_deposits`, `deposit_stream_threshold`, `deposit_stream_source` = `history`|`override`|`default`, `deposit_stream_decided_at`; internal audit only, never projected to the merchant). ADMIN-ONLY: a merchant-scoped key answers `403 forbidden` — the threshold is the PSP contract condition, not a casino preference. Error split: a missing/non-integer value is the body-parser rejection (`400 invalid_request`); a well-formed INTEGER outside `1..=2147483647` (`< 1` or `> i32::MAX`) is `422 invalid_request` (a zero threshold would send a payer with no history to STD and disable the FTD terminal). The change and its `merchant.std_min_deposits` audit event (previous value, new value, free-text reason) are committed in one transaction. A foreign or unknown merchant is a plain `404`.",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "std_min_deposits"
                ],
                "properties": {
                  "std_min_deposits": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 2147483647,
                    "description": "The number of SUCCESSFUL customer deposits after which the payer is STD (redep) traffic. Must be an integer in `1..=2147483647`: a missing/non-integer value is the body-parser rejection (`400 invalid_request`), an integer outside the range (`< 1` or `> i32::MAX`) is `422 invalid_request`."
                  },
                  "reason": {
                    "type": "string",
                    "description": "Free-text operator reason (e.g. the contract clause), recorded in the audit event verbatim."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The settled threshold.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "merchant_id": {
                      "type": "string",
                      "example": "mer_01900000-0000-7000-8000-000000000001"
                    },
                    "std_min_deposits": {
                      "type": "integer",
                      "minimum": 1
                    }
                  },
                  "required": [
                    "merchant_id",
                    "std_min_deposits"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`) — the threshold is an operator/contract surface.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Merchant not found in this tenant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "400": {
            "description": "Malformed body — `std_min_deposits` missing or not a JSON integer (`invalid_request`, the body-parser rejection).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Well-formed integer `std_min_deposits` outside `1..=2147483647` — below 1 or above `i32::MAX` (`invalid_request`): a threshold of 0/negative would route a payer with no history to STD.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/payouts-enabled": {
      "put": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Toggle the per-merchant payouts gate (PA-83, PA-97)",
        "description": "The OPERATOR toggle of the per-merchant payouts gate (PA-83). ADMIN-ONLY: a merchant-scoped key answers `403 forbidden` — the money-out direction is an operator decision (AML/fraud review, contract terms); a casino must not enable its own payout surface. The change and its `payout.payouts_enabled` audit event (enabled value + free-text `reason` verbatim) are committed in one transaction. PA-97: the merchant-scoped payout surface (`POST /v1/merchants/{id}/payouts`) requires the TENANT-level gate (`tenants.payouts_enabled`, PUT `/v1/tenants/{id}/payouts-enabled`) AND this flag — both fail-closed. A foreign or unknown merchant is a plain `404`.",
        "operationId": "setMerchantPayoutsEnabled",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SetMerchantPayoutsEnabledRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The settled gate state.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SetMerchantPayoutsEnabledResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`) — the payouts gate is an operator surface.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Merchant not found (`merchant_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/webhooks/deliveries/{delivery_id}/retry": {
      "post": {
        "tags": [
          "Merchant Portal"
        ],
        "summary": "Manually re-deliver one webhook delivery",
        "description": "Manual re-delivery of ONE webhook delivery row (PA-86, QA-91 #5; the `/portal` Events-and-Logs «Re-send» control): the row is re-queued into the PA-40 outbox — `status` returns to `PENDING` and the next worker tick claims it immediately. A `PENDING` row skips the remaining backoff wait; a `DEAD` (dead-letter) row gets exactly ONE fresh dispatch attempt — the attempt counter is NOT reset, so a re-queued DEAD row that fails again dead-letters on the spot. A `DELIVERED` row is never re-sent (the receiver already confirmed with 2xx): the endpoint answers `409 delivery_already_delivered`. The stored payload bytes are re-delivered verbatim — at-least-once delivery, receivers dedup by `event_id`. Audited as `merchant.webhook_redelivered` in the same transaction as the re-queue. Strictly merchant-scoped: the delivery must belong to the path merchant and the merchant to the caller's tenant — a foreign or unknown delivery is a plain `404`. Same admin Bearer (or the merchant's own scoped key).",
        "operationId": "retryMerchantWebhookDelivery",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "$ref": "#/components/parameters/DeliveryId"
          }
        ],
        "responses": {
          "200": {
            "description": "Delivery re-queued (`status` back to `PENDING`, due immediately)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantWebhookDeliveryResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Delivery (or merchant) not found in this tenant (`delivery_not_found` / `merchant_not_found`) — a foreign delivery is never confirmed to exist",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Delivery is DELIVERED — never re-sent (`delivery_already_delivered`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/webhooks/deliveries/{delivery_id}/resend": {
      "post": {
        "tags": [
          "Merchant Portal"
        ],
        "summary": "Re-send one webhook delivery to a chosen address (one-off)",
        "description": "Manual ONE-OFF re-send of ONE delivery (PA-149; the Admin v2 «Журнал доставок» → «Перевідправити на адресу…»).\n\nThe endpoint creates a NEW delivery row: the same `payment_id`/`payout_id`/`event_type`/`payload`, `status` = `PENDING`, `attempts` = 0, a FRESH `event_id` (the receiver dedups by `PA-Event-Id`, so a re-send under the original id would be silently swallowed — that is exactly what this operation exists to avoid), `target_url` = the address from the request body and `resend_of` = the addressed delivery id. The new row is dispatched by the ordinary PA-40 ladder (backoff, dead letter) and signed with the merchant's webhook secret (PA-13/PA-34) — the target changes WHERE the bytes go, never WHO signs them.\n\n**The merchant's registered webhook endpoint is NOT changed**: `merchants.webhook_url` is never written by this operation, so every future event still goes to the registered endpoint (the worker dispatches `COALESCE(target_url, webhook_url)`). **The original delivery is NOT rewritten**: its `status`/`attempts`/`last_error` stay as they are — this is a separate row, not the PA-86 `retry` which re-queues the same row to the registered endpoint.\n\nThe `url` is validated: `http(s)`, at most 2048 characters, a non-empty host, no userinfo credentials; loopback/private/link-local/metadata hosts are rejected outside `dev` (SSRF gate). Audited as `webhook.resent_manually` with the masked target host (the query string is dropped) in the same transaction as the insert. Strictly merchant-scoped: a foreign or unknown delivery is a plain `404`; a merchant without a registered webhook is `409 webhook_not_registered` (there is no secret to sign with); a pinned `event_id` that already exists is `409 event_id_already_used`.",
        "operationId": "resendMerchantWebhookDelivery",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "$ref": "#/components/parameters/DeliveryId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ResendWebhookDeliveryRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The NEW delivery row (PENDING, `target_url` + `resend_of` set, fresh `event_id`)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MerchantWebhookDeliveryResponse"
                }
              }
            }
          },
          "400": {
            "description": "Malformed request body (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Delivery (or merchant) not found in this tenant (`delivery_not_found` / `merchant_not_found`) — a foreign delivery is never confirmed to exist",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`webhook_not_registered` (no signing secret — no registered webhook) or `event_id_already_used` (the pinned `event_id` describes another delivery)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "The target URL is invalid — non-http(s), missing host, userinfo credentials, over 2048 characters, or an internal (loopback/private/link-local/metadata) host outside `dev` (`invalid_request`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          }
        }
      }
    },
    "/v1/merchants/{id}/providers/{code}": {
      "put": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Toggle one payment provider for the merchant (PA-105, per-connector AND per-sub-provider)",
        "description": "Merchant self-service enablement of ONE payment provider: `enabled=false` removes the provider's route targets from the routing eligibility of this merchant's NEW payments (in-flight payments finish as usual — the continuation is unaffected); `enabled=true` re-enables. The base PSP set stays the operator's routing configuration — the merchant can only narrow it, never widen it. The provider code must be one the operator actually configured for the merchant (an unknown code is a plain 404). The toggle is audited as `merchant.provider_toggled` in the same transaction as the change. Disabling the LAST enabled PSP is not blocked (the toggle is reversible) but the response carries `last_enabled: true` — acceptance of payments stops until another PSP is re-enabled. PA-105 granularity: a body `sub_provider` (Apcopay `provider_routing.bank_code`, PA-112) scopes the toggle to ONE sub-provider of the connector — a sub-provider the operator has NOT configured for the merchant is a plain 404; the absent field keeps the MASTER semantics (the whole connector, every sub-provider included). A master toggle off turns ALL sub-providers off with it; a sub toggle leaves the rest of the connector working. PA-116/PA-117 — the ADMIN key has TWO disabling actions: the SOFT disable (`enabled=false` without `operator_locked`, or `operator_locked=false`) keeps the row merchant-visible and merchant-reversible (the PA-105 semantics), the OPERATOR-ENFORCED disable (`enabled=false, operator_locked=true`) hides the PSP from the merchant cabinet — the merchant-scope re-enable answers `403 provider_locked_by_operator` and only the admin `enabled=true` clears the lock (unlock + re-enable). The audit event follows the LOCK-STATE CHANGE of the row: a lock/unlock flip is `merchant.provider_locked` (details carry the settled `locked` flag), a same-lock-state write (soft disable, plain enable, any merchant toggle) is `merchant.provider_toggled`. The MERCHANT scope may toggle only unlocked rows: a locked target row (or a toggle under a connector whose master row is locked) answers `403 provider_locked_by_operator` — and a locked target answers 403 regardless of `operator_locked` presence in the request (`403` takes precedence over the `422 operator_locked_is_operator_only` check for the operator-only field) — both answers leave the stored state unchanged.",
        "operationId": "setMerchantProviderEnabled",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "$ref": "#/components/parameters/ProviderCode"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SetMerchantProviderRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The settled state of the toggled PSP",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SetMerchantProviderResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant or provider code not found for this merchant (`merchant_not_found`)",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "403": {
            "description": "The PSP is operator-locked (`provider_locked_by_operator`): it was disabled by the operator (PA-116) and the merchant cannot re-enable it — contact support. The stored state is unchanged.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "A merchant-scope request carrying the operator-only `operator_locked` field (`operator_locked_is_operator_only`): the merchant can never set or clear the operator lock; the stored state is unchanged.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/payouts/{payout_id}/approve": {
      "post": {
        "tags": [
          "Merchant Payouts"
        ],
        "summary": "Approve this merchant's payout (self-approval)",
        "description": "The MERCHANT self-approval (PA-107): the casino confirms its OWN payout while it sits at the approval gate — `AWAITING_APPROVAL` → `APPROVED`, same semantics as the operator approve: the payout limits are re-checked at the decision point, the approved snapshot is fixed and a `merchant`-role decision is appended to `approval_decisions[]`. Gated fail-closed by the operator toggle `merchants.payout_self_approval` (PUT `/v1/merchants/{id}/payout-self-approval`, audited `merchant.payout_self_approval`): while the flag is off the surface answers `422 payout_self_approval_not_enabled` and the operator four-eyes decision stands. A foreign payout is a plain `404`. Idempotent; empty body allowed (`reason` optional).",
        "operationId": "approveMerchantPayout",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "$ref": "#/components/parameters/PayoutId"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PayoutMutationRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The payout is `APPROVED` (or the replayed stored result).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found (`merchant_not_found`) or the payout does not belong to this merchant (`payout_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Idempotency key in flight (`idempotency_in_flight`), a payout outside `AWAITING_APPROVAL` (`payout_already_final` — final, dispatched, or not yet submitted for approval) or a concurrent modification (`invalid_state_transition`).",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Payouts not enabled for this merchant (`payouts_not_enabled`), the self-approval flag is off (`payout_self_approval_not_enabled`) or idempotency key reuse (`idempotency_key_reuse`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/payouts/{payout_id}/decline": {
      "post": {
        "tags": [
          "Merchant Payouts"
        ],
        "summary": "Decline this merchant's payout (self-approval)",
        "description": "The MERCHANT self-decline (PA-107): the casino declines its OWN payout while it sits at the approval gate — `AWAITING_APPROVAL` → `DECLINED`, the `merchant`-role decision is appended to `approval_decisions[]` and the limit reservations are released (proven non-execution). Same fail-closed flag gate and ownership rules as the merchant approve. A foreign payout is a plain `404`. Idempotent; empty body allowed (`reason` optional).",
        "operationId": "declineMerchantPayout",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "$ref": "#/components/parameters/PayoutId"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PayoutMutationRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The payout is `DECLINED` (or the replayed stored result).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PayoutResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Merchant not found (`merchant_not_found`) or the payout does not belong to this merchant (`payout_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Idempotency key in flight (`idempotency_in_flight`), a payout outside `AWAITING_APPROVAL` (`payout_already_final` — final, dispatched, or not yet submitted for approval) or a concurrent modification (`invalid_state_transition`).",
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Payouts not enabled for this merchant (`payouts_not_enabled`), the self-approval flag is off (`payout_self_approval_not_enabled`) or idempotency key reuse (`idempotency_key_reuse`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/payout-self-approval": {
      "put": {
        "tags": [
          "Merchant Onboarding"
        ],
        "summary": "Toggle the merchant payout self-approval flag (PA-107)",
        "description": "The OPERATOR toggle of the merchant payout SELF-approval flag (PA-107, `merchants.payout_self_approval`, migration 0027). ADMIN-ONLY: a merchant-scoped key answers `403 forbidden` — the merchant may not grant itself the four-eyes waiver. The change and its `merchant.payout_self_approval` audit event (enabled value + free-text `reason` verbatim) are committed in one transaction. Fail-closed: `false` (the default) keeps the operator approval gate — the merchant creates payouts, the OPERATOR decides them. `true` opens the merchant self-approval surface (`POST /v1/merchants/{id}/payouts/{payout_id}/approve|decline`, the `/portal` Payouts tab buttons). A foreign or unknown merchant is a plain `404`.",
        "operationId": "setMerchantPayoutSelfApproval",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SetMerchantPayoutSelfApprovalRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The settled flag state.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SetMerchantPayoutSelfApprovalResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "The Bearer is a merchant-scoped key, not the admin (tenant) key (`forbidden`) — the self-approval waiver is an operator surface.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Merchant not found (`merchant_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp/{connector}/callback": {
      "post": {
        "tags": [
          "PSP Callbacks"
        ],
        "summary": "PSP settlement callback receiver (PA-108)",
        "description": "The receiver the providers deliver settlement callbacks to (`CallBackURL` of the Apcopay HPP request; the BTQ Finance `postbackUrl`).\n\nContract per connector:\n- **apcopay** — the payload is AUTHORITATIVE after verification: the `Signature` header (`Base64(HMAC-SHA256(<concat>, Merchant Secret))`, `<concat>` = the Apcopay signature calculation over the JSON body — flatten, case-insensitive key sort, `k=v` join, whole-string lowercase) MUST verify, else `401` (the received header value is never echoed). Statuses: `Processed` → payment `AUTHORIZED`, `Declined` → `FAILED`, `Pending` → no change.\n- **btqfin** (alias `btqfi`) — NO documented signature: the postback is an UNAUTHENTICATED TRIGGER. PA never applies the payload status; it re-asks the PSP through the authenticated sync path and projects THAT answer (a forged postback cannot mint a state change).\n\nIdempotency: the event identity is `(connector, external id, status)` — the Apcopay `PspId` / BTQ Finance `paymentId` plus the status word. A redelivery (the PSP retry ladder raises `AttemptNumber`) is the same event: acknowledged `200` without changes and without a second merchant webhook event.\n\nFail-closed: a callback naming no PA attempt is acknowledged `200` and logged (reconciliation remains the backstop); an unknown connector is a plain `404`; an unconfigured signature secret is `503`. ACK: `200` with `{\"received\": true}`.\n\nLookup: the attempt is resolved by the PSP transaction reference stored at authorize time (`attempts.provider_transaction_id`) within the connector namespace of the path.",
        "operationId": "pspCallback",
        "parameters": [
          {
            "name": "connector",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Connector code of the callback contract (lowercase): `apcopay`, `btqfin` (alias `btqfi`). Any other value answers `404 unknown_connector`."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              },
              "example": {
                "AttemptNumber": 1,
                "SentDateTime": "2026-10-16T12:00:00Z",
                "Status": "Processed",
                "PspId": 850907,
                "OrderReference": "OrderRef001",
                "Amount": "25.00",
                "Currency": "EUR"
              }
            }
          }
        },
        "security": [],
        "responses": {
          "200": {
            "description": "Callback accepted (applied, duplicate, non-terminal, unmapped or trigger-without-result). Body: `{\"received\": true}` — the PSP retries only on non-2xx."
          },
          "400": {
            "description": "The payload failed the documented schema (signature was valid) — `invalid_callback_payload`."
          },
          "401": {
            "description": "Missing/invalid `Signature` header (apcopay) — `unauthorized`; the received value is not echoed."
          },
          "404": {
            "description": "Unknown connector path — `unknown_connector`."
          },
          "429": {
            "description": "Per-IP callback window exhausted — `rate_limited` + `Retry-After`."
          },
          "503": {
            "description": "No signature secret configured for this connector — `psp_callback_not_configured` (fail-closed)."
          }
        }
      }
    },
    "/v1/payment-methods/{id}": {
      "patch": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Edit a global payment method",
        "description": "PA-136: name, description, supported_operations and lifecycle status. `code` and `routing_category` are IMMUTABLE (the routing key and the cascade bucket) and are not part of the body. Audited `payment_method.updated` with before/after.",
        "operationId": "updatePaymentMethod",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Payment method id."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdatePaymentMethodRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "Payment method not found (`method_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`payment_method_name_exists` (case-insensitive).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure: `invalid_request`, `invalid_supported_operations`, `invalid_status`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "The updated method definition.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaymentMethodDefinition"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/credential-fields/order": {
      "put": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Reorder a credential schema slot",
        "description": "PA-136: the drag order of ONE schema slot (`scope` + `terminal_template_id` for terminal slots; `scope` alone for the PSP slots). Atomic: the submitted ids take `position = (index+1)*10`, the fields of the slot that are NOT submitted follow in their current order. Every submitted id must belong to the requested slot: a foreign/unknown id or a duplicate answers `422 field_ids_mismatch`. Audited `credential_field.reordered`.",
        "operationId": "reorderCredentialFields",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "scope",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "merchant_account",
                "terminal",
                "webhook",
                "operation_specific"
              ]
            },
            "description": "Credential schema scope. `terminal` fields attach to `terminal_template_id`; `merchant_account`/`webhook`/`operation_specific` fields attach to the PSP itself."
          },
          {
            "name": "terminal_template_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Terminal template of a `scope=terminal` schema slot."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ReorderCredentialFieldsRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `terminal_template_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "`field_ids_mismatch`, `invalid_scope`, `terminal_template_required`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "The re-ordered schema slot.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CredentialFieldListResponse"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/credential-fields/{field_id}": {
      "patch": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Edit one credential schema field",
        "description": "PA-136: edit a field WITHOUT touching its `key`, `scope` or parent — renaming the JSON key of the credentials object would orphan the already-sealed merchant values. The merged result is re-validated: `is_secret=true` forbids `default_value`, `select` requires a non-empty `select_options`, `environment ∈ {sandbox,live}` or null. Audited `credential_field.updated` with the non-secret before/after.",
        "operationId": "updateCredentialField",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "field_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Credential field id."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateCredentialFieldRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `credential_field_not_found` (a foreign field is a plain 404).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure: `invalid_field_type`, `secret_default_value_forbidden`, `secret_field_type_requires_secret`, `select_options_required`, `invalid_select_options`, `invalid_validation`, `invalid_environment`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "The updated schema field.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CredentialFieldDefinition"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Remove one credential schema field",
        "description": "PA-136: removes the schema row. While live terminal instances carry sealed credentials the delete is `409 field_in_use` with the connection/terminal counters; `?force=1` removes the schema row anyway (the sealed merchant values are never touched — they become undeclared, which is exactly what the operator acknowledged). Audited `credential_field.deleted`.",
        "operationId": "deleteCredentialField",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "field_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Credential field id."
          },
          {
            "name": "force",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "1",
                "0"
              ]
            },
            "description": "Acknowledge the guarded mutation (`1`/`true`/`yes`). For `terminal_policy` it admits the change once the EXISTING terminal data is compatible with the NEW policy; it never deletes terminals or routes."
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `credential_field_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`field_in_use` (problem `details` carry the counters and `force_supported`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "204": {
            "description": "Schema field removed."
          }
        }
      },
      "put": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Edit one credential schema field (PUT alias)",
        "description": "PA-136: edit a field WITHOUT touching its `key`, `scope` or parent — renaming the JSON key of the credentials object would orphan the already-sealed merchant values. The merged result is re-validated: `is_secret=true` forbids `default_value`, `select` requires a non-empty `select_options`, `environment ∈ {sandbox,live}` or null. Audited `credential_field.updated` with the non-secret before/after. **PA-139 (A1):** `PUT` is a registered ALIAS of the same handler — the whole-slot replacement, same body, same response, same `credential_field.updated` audit event. The Admin v2 schema editor has always sent `PUT`; before this alias the request answered `405` and the operator's edit survived only in the tab memory.",
        "operationId": "replaceCredentialField",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "field_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Credential field id."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateCredentialFieldRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `credential_field_not_found` (a foreign field is a plain 404).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure: `invalid_field_type`, `secret_default_value_forbidden`, `secret_field_type_requires_secret`, `select_options_required`, `invalid_select_options`, `invalid_validation`, `invalid_environment`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "The updated schema field.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CredentialFieldDefinition"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/credential-fields": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List the credential schema of a catalog PSP",
        "description": "PA-136: the DYNAMIC credential schema — terminal-scoped fields of every template plus the PSP-scoped merchant_account/webhook/operation_specific fields. Optional `scope` and `terminal_template_id` filters. Schema only: no credential VALUE is ever returned (ADR-0008 §3).",
        "operationId": "listCredentialFields",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "scope",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "merchant_account",
                "terminal",
                "webhook",
                "operation_specific"
              ]
            },
            "description": "Credential schema scope. `terminal` fields attach to `terminal_template_id`; `merchant_account`/`webhook`/`operation_specific` fields attach to the PSP itself."
          },
          {
            "name": "terminal_template_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Terminal template of a `scope=terminal` schema slot."
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `terminal_template_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "`invalid_scope`, `credential_scope_parent_conflict`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "The credential schema fields of the PSP.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CredentialFieldListResponse"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Add one credential schema field",
        "description": "PA-136: adds one field to the dynamic credential schema. Exactly one parent: `scope=terminal` requires `terminal_template_id` and must NOT carry the PSP as a parent; the other scopes attach to the PSP and must NOT carry a template. `key` is snake_case (`^[a-z][a-z0-9_]{1,63}$`) and unique in its scope; `field_type` is one of the 10 values of the widened 0041 vocabulary. `is_secret=true` forbids `default_value`; `select` requires a non-empty `select_options`; `validation` is a JSON object; `environment ∈ {sandbox,live}` or null. Audited `credential_field.created` (no values).",
        "operationId": "createCredentialField",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateCredentialFieldRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `terminal_template_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`duplicate_field_key` (unique in its scope).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Validation failure: `invalid_field_key`, `invalid_field_type`, `secret_default_value_forbidden`, `select_options_required`, `invalid_select_options`, `invalid_validation`, `invalid_environment`, `terminal_template_required`, `credential_scope_parent_conflict`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "201": {
            "description": "The created schema field.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CredentialFieldDefinition"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/terminal-templates": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List the terminal templates of a catalog PSP",
        "description": "PA-136: template rows with their assigned `method_ids` (terminal_template_methods) and the credential-schema field counts (total/required). **PA-143:** each row also carries `code`/`environment` (migration 0047), the resolved `methods: [{id, code, name}]` and the FULL `fields: CredentialFieldDefinition[]`; the three collections are read with THREE batched queries per page (no N+1).",
        "operationId": "listTerminalTemplates",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "The terminal templates of the PSP.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TerminalTemplateListResponse"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Create a terminal template",
        "description": "PA-136. `allow_multiple=false` means exactly one instance (`min=max=1`, normalized); otherwise `min_instances >= 1` and `max_instances >= min_instances` (null = unlimited). The PSP terminal policy governs the count: `NONE` answers `409 psp_has_no_terminals`, `SHARED` admits exactly one template (`409 shared_policy_single_template`). `method_ids` must be declared by the PSP through `psp_methods`. Audited `terminal_template.created`. **PA-143:** `code` (UPPER_SNAKE, 2–32, unique per PSP, nullable) and `environment` (`sandbox|live|both`, default `both`) are persisted and audited; a duplicate code answers `409 terminal_template_code_exists`, a malformed code `422 invalid_template_code`, a foreign environment `422 invalid_environment` (both carry `details.field`).",
        "operationId": "createTerminalTemplate",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateTerminalTemplateRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `method_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`psp_has_no_terminals`, `shared_policy_single_template` or `terminal_template_already_exists` (the name is unique per PSP). **PA-143:** also `terminal_template_code_exists`, and the SAME 409 is returned when two concurrent creates race on one code (SQLSTATE 23505 on `uq_terminal_templates_psp_code`) — a race loser never surfaces as a 500.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "`invalid_instance_bounds`, `method_not_assigned_to_psp`, `invalid_request`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "201": {
            "description": "The created template with methods and field counts.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TerminalTemplateSummary"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/terminal-templates/{template_id}": {
      "patch": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Edit a terminal template",
        "description": "PA-136: name, description and instance bounds. The owning PSP is immutable. `allow_multiple=false` NORMALIZES the bounds to `min=max=1`. Audited `terminal_template.updated` with before/after. **PA-143:** `code`/`environment` are accepted (`code: null` clears, an absent key is unchanged); the same 409/422 vocabulary as POST applies.",
        "operationId": "updateTerminalTemplate",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Terminal template id."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateTerminalTemplateRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `terminal_template_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`terminal_template_already_exists` (the name is unique per PSP). **PA-143:** also `terminal_template_code_exists`. The same 409s are used for a concurrent-code race (SQLSTATE 23505).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "`invalid_instance_bounds`, `invalid_request`. **PA-143:** also `invalid_template_code` / `invalid_environment`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "The updated template with methods and field counts.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TerminalTemplateSummary"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Remove a terminal template",
        "description": "PA-136: only a template WITHOUT merchant terminal instances is removable. With instances the answer is `409 template_in_use`; `?force=1` is NOT supported here (it would have to delete merchant terminals and their routes) — the same 409 carries `force_supported: false` so the UI can disable the force action. Audited `terminal_template.deleted`.",
        "operationId": "deleteTerminalTemplate",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Terminal template id."
          },
          {
            "name": "force",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "1",
                "0"
              ]
            },
            "description": "Acknowledge the guarded mutation (`1`/`true`/`yes`). For `terminal_policy` it admits the change once the EXISTING terminal data is compatible with the NEW policy; it never deletes terminals or routes."
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `terminal_template_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`template_in_use` (`force_supported: false`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "204": {
            "description": "Template removed."
          }
        }
      },
      "put": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Edit a terminal template (PUT alias)",
        "description": "PA-136: name, description and instance bounds. The owning PSP is immutable. `allow_multiple=false` NORMALIZES the bounds to `min=max=1`. Audited `terminal_template.updated` with before/after. **PA-139 (A2):** `PUT` is a registered ALIAS of the same handler (same body, response and `terminal_template.updated` audit event); the «Save Template» button sends `PUT`, which answered `405` before the alias.",
        "operationId": "replaceTerminalTemplate",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Terminal template id."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateTerminalTemplateRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `terminal_template_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "`terminal_template_already_exists` (the name is unique per PSP).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "`invalid_instance_bounds`, `invalid_request`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "The updated template with methods and field counts.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TerminalTemplateSummary"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/terminal-templates/{template_id}/methods": {
      "put": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Replace the method set of a terminal template",
        "description": "PA-136: replaces `terminal_template_methods` for the template (the body is the FULL new set; an empty list clears it). Every method must exist and be declared by the PSP through `psp_methods`. Audited `terminal_template.methods_changed` with the previous/new sets. This is the ONLY way to bind methods to a template (`psp_methods` has no template column): the console diffs its checkbox set against every template's `methods` and sends one `PUT` per changed template; an empty `method_ids` detaches the template from every method (account-level binding).",
        "operationId": "replaceTerminalTemplateMethods",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Terminal template id."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ReplaceTerminalTemplateMethodsRequest"
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `terminal_template_not_found` / `method_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "`method_not_assigned_to_psp`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "The updated template with methods and field counts.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TerminalTemplateSummary"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/psp-connections/{conn}/restore": {
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Restore an archived connection",
        "description": "Clears the soft-archive marker of the connection and its terminals. `409 credentials_missing` when the stored credentials are absent or invalid (the `merchant_account`/`operation_specific` scopes — a required `webhook` field does NOT block) and `409 psp_disabled_globally` while the PSP is globally disabled (the archive is left intact). The terminals come back one per (connection, template, name): the most recently archived row of a name group. An older archived duplicate whose name is now held by a LIVE terminal stays archived (migration 0044 — the live-only name key is never violated). Admin-only. Idempotent for a live connection. Audited `merchant_connection.restored`.",
        "operationId": "restoreMerchantPspConnection",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The restored connection detail."
          },
          "403": {
            "description": "Admin key required.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Connection not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Credentials missing or invalid.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/psp-connections/{conn}/credentials": {
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Write connection credentials",
        "description": "Writes the API-auth (`merchant_account`), webhook-verification (`webhook`) or operation-specific credentials of one scope. The values are PATCH-merged (an empty value never overwrites) and envelope-encrypted (AES-256-GCM DEK + KEK); the response reports WHICH fields are configured — a value is never returned and never audited. Admin-only.",
        "operationId": "writeMerchantConnectionCredentials",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "scope": {
                    "type": "string",
                    "enum": [
                      "merchant_account",
                      "webhook",
                      "operation_specific"
                    ]
                  },
                  "credentials": {
                    "type": "object",
                    "additionalProperties": true,
                    "description": "{field_key: value}. An empty value never overwrites the stored one."
                  }
                },
                "required": [
                  "scope"
                ]
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Configured field flags."
          },
          "403": {
            "description": "Admin key required.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Connection not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Archived connection.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Unknown field / empty payload / KEK missing.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/psp-connections/{conn}/credentials/{scope}/rotate": {
      "post": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Rotate connection credentials",
        "description": "Re-seals one credential scope with a fresh data key (envelope rotation), PATCH-merging the submitted values. Admin-only; audited `merchant_connection.credentials_updated` with `rotate: true`.",
        "operationId": "rotateMerchantConnectionCredentials",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "scope",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "enum": [
                "merchant_account",
                "webhook",
                "operation_specific"
              ]
            }
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "credentials": {
                    "type": "object",
                    "additionalProperties": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Configured field flags."
          },
          "403": {
            "description": "Admin key required.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Connection not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Archived connection.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Unknown field / empty payload / KEK missing.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/psp-connections/{conn}/terminals": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List the terminals of one connection",
        "description": "The terminals of ONE merchant connection (archived ones carry `archived_at`). Credentials are never returned — only `credentials_present` and the fingerprint.",
        "operationId": "listConnectionTerminals",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The connection's terminals."
          },
          "404": {
            "description": "Connection not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/terminals/{terminal_id}": {
      "patch": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Edit a terminal",
        "description": "Renames a terminal, flips its status (`ENABLED|DISABLED`) and/or binds it to an executing Route Target (`route_target_id`; `null` clears the binding). The Route Target must belong to the merchant and its provider connector must equal the PSP `technical_id`. `ENABLED` requires a binding AND usable credentials (`409 terminal_not_ready`). Admin-only; audited `merchant_terminal.status_changed` with before/after. Renaming onto a name already taken by a LIVE terminal in the connection answers `409 terminal_name_exists` (detail carries `connection_id`, `terminal_template_id`, `name`); an ARCHIVED terminal's name is reusable.",
        "operationId": "updateMerchantTerminal",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string",
                    "maxLength": 255,
                    "description": "New terminal name, unique per (connection, template) among LIVE terminals only — an ARCHIVED terminal's name can be reused; a clash with a live terminal answers `409 terminal_name_exists`."
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "ENABLED",
                      "DISABLED"
                    ]
                  },
                  "route_target_id": {
                    "type": "string",
                    "format": "uuid",
                    "nullable": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The updated terminal."
          },
          "403": {
            "description": "Admin key required.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Terminal or route target not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "terminal_not_ready / terminal_archived, or terminal_name_exists when the name is taken by a LIVE terminal in the connection (an ARCHIVED terminal's name is reusable).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Invalid name/status or a foreign route target.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Delete (archive) a terminal",
        "description": "Soft-deletes the terminal. A terminal still bound to cascade routes answers `409 terminal_has_routes` unless `?force=1`, which removes exactly those routes and reports their ids. Admin-only; audited `merchant_terminal.archived`.",
        "operationId": "archiveMerchantTerminal",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "force",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "`1`/`true` removes the bound routes."
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The removed route ids."
          },
          "403": {
            "description": "Admin key required.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Terminal not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "The terminal still has routes.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/terminals/{terminal_id}/credentials": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Read terminal credential presence",
        "description": "Which credential FIELDS are configured (presence flags only — a value is never returned).",
        "operationId": "getMerchantTerminalCredentials",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Configured field flags."
          },
          "404": {
            "description": "Terminal not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      },
      "put": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Write terminal credentials",
        "description": "Replaces the terminal credentials against its template schema (PATCH merge; required fields must end up present). Envelope-encrypted like the create path (fail-closed without a KEK); audited with the fingerprint only. Admin-only.",
        "operationId": "putMerchantTerminalCredentials",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "credentials": {
                    "type": "object",
                    "additionalProperties": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Configured field flags."
          },
          "403": {
            "description": "Admin key required.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "404": {
            "description": "Terminal not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "409": {
            "description": "Archived terminal.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Unknown/missing field or KEK missing.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/routing-preview": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "Preview routing eligibility",
        "description": "A PURE evaluation over the stored configuration (nothing is written): which routes of the cascade are eligible for the given transaction and WHY the others are not. Structural reasons (the same gate the cascade read reports): `connection_not_enabled` (the connection is not `enabled` — `available`, `blocked` or `draft` — and is not archived; the PSP itself is fine), `psp_blocked` (a PSP-level verdict: a `hidden` connection OR a PSP switched off globally by the operator), `terminal_disabled`, `route_target_unbound` (PA-137: an account-level route without an explicit Route Target — it has no executing PSP), `method_hidden`, `route_disabled`, `missing_credentials`, `disconnected`. Query-dependent reasons: `currency_unsupported`, `geo_unsupported`, `amount_out_of_range`, `operation_not_supported`.",
        "operationId": "routingPreview",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          },
          {
            "name": "method",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "Method UUID or code (its category selects the cascade)."
          },
          {
            "name": "category",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "CARD",
                "APPLE_PAY",
                "GOOGLE_PAY",
                "OPEN_BANKING",
                "BANK_TRANSFER"
              ]
            }
          },
          {
            "name": "transaction_type",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "deposit",
                "payout"
              ]
            },
            "description": "Default `deposit`."
          },
          {
            "name": "segment",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "currency",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "ISO 4217."
          },
          {
            "name": "country",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "ISO 3166-1 alpha-2."
          },
          {
            "name": "amount",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "format": "int64"
            },
            "description": "Minor units."
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "Eligible and excluded routes."
          },
          "404": {
            "description": "Cascade or method not found.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "422": {
            "description": "Neither category nor method, or an invalid value.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/merchants/{id}/routing-segments": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List the merchant's routing segments",
        "description": "Every configured cascade of the merchant as a (segment, transaction_type, method_category) triple with its route count — the segment selector of the cascade editor.",
        "operationId": "listRoutingSegments",
        "parameters": [
          {
            "$ref": "#/components/parameters/MerchantId"
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The configured segments."
          }
        }
      }
    },
    "/v1/audit/export.csv": {
      "get": {
        "tags": [
          "Admin"
        ],
        "summary": "Export the audit trail as CSV",
        "description": "Streams the audit log as CSV with exactly the filters of `GET /v1/audit`. The audit trail never stores credential values, so the export cannot leak one. Admin-only.",
        "operationId": "exportAuditCsv",
        "parameters": [
          {
            "name": "q",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "actor",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "merchant_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "psp_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "entity_type",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "entity_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "action",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "maximum": 500
            }
          },
          {
            "name": "before_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "format": "int64"
            }
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The CSV stream (text/csv).",
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "400": {
            "description": "Invalid filter value.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/meta/capabilities": {
      "get": {
        "tags": [
          "Admin"
        ],
        "summary": "Feature capabilities of the admin surface",
        "description": "The feature flags the Admin v2 UI branches on — the UI must never invent a capability the backend does not have. `test_connection`/`test_terminal` are false (no live probes), `audit_export` is true and `roles` is false (single admin key). `cascades_execution` is true since PA-136: a routing cascade with at least one route is the AUTHORITATIVE order of deposits (`POST /v1/payments`) — when no route of it is eligible the answer is `422 no_eligible_route`; a cascade with zero routes (or no cascade) falls back to the legacy Route Target order. Since PA-137 the flag also covers the SEGMENTED cascades (the request's `segment` selects the cascade; a segment without one falls back to the default cascade), the ACCOUNT-LEVEL routes (an explicit `routing_cascade_routes.route_target_id` executes without a terminal; an unbound one answers `route_target_unbound`) and the IN-FLIGHT continuation of an already-started payment (the cascade order without re-trying a dispatched target, `DRAINING` terminals still execute, and an empty intersection falls back to the legacy order instead of any refusal). The flag does NOT cover payouts (payout cascades do not execute).",
        "operationId": "getCapabilities",
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The feature flags."
          },
          "403": {
            "description": "Admin key required.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/terminal-templates/{template_id}/terminals": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List the terminals created from one terminal template (drill-down)",
        "description": "PA-144: the answer to «where are these 26 terminals?». Live terminal instances of every merchant that were created from THIS template — the same population the policy/quota guards count (an archived terminal or an archived connection is NOT listed: it occupies no slot and no route). Ordered by `merchant_name, terminal_name, terminal_id`; `limit` defaults to 25 and is capped at 100. Admin-only and TENANT-scoped: the catalog PSP is global, but the terminal instances belong to the merchants (tenant) of the calling admin key, so another tenant's terminals are never visible. Credentials are never projected. UI: PSP Catalog → Terminals → the «терміналів: N» counter.",
        "operationId": "listTerminalTemplateTerminals",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Terminal template id."
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "format": "int64",
              "default": 25,
              "minimum": 1,
              "maximum": 100
            },
            "description": "Page size (`>100` is clamped to 100)."
          },
          {
            "name": "offset",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "format": "int64",
              "default": 0,
              "minimum": 0
            },
            "description": "Rows to skip (`<0` is `400 invalid_request`)."
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "`forbidden` — the caller is a merchant-scoped key, not the admin principal.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found` / `template_not_found` (also for a template of ANOTHER catalog PSP).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "400": {
            "description": "`invalid_request` — `limit <= 0`, `offset < 0` or a malformed number.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "One page of the live terminals created from this template, ordered by `merchant_name, terminal_name`; `total` is the unpaged population.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CatalogTerminalListResponse"
                }
              }
            }
          }
        }
      }
    },
    "/v1/psp-catalog/{id}/terminals": {
      "get": {
        "tags": [
          "PSP Management"
        ],
        "summary": "List every terminal of a catalog PSP (all templates)",
        "description": "PA-144: the «Усі термінали PSP» screen — every terminal of every template of the PSP in one page, each row naming the template it was created from. `search` is a LITERAL substring over `merchant_name`/`terminal_name` (LIKE-escaped: `%`, `_` and `!` match themselves). Ordered by `merchant_name, terminal_name, terminal_id`; `limit` defaults to 25 and is capped at 100. Admin-only and tenant-scoped (see the per-template list), archive excluded, credentials never projected.",
        "operationId": "listPspCatalogTerminals",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Catalog PSP id."
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "format": "int64",
              "default": 25,
              "minimum": 1,
              "maximum": 100
            },
            "description": "Page size (`>100` is clamped to 100)."
          },
          {
            "name": "offset",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "format": "int64",
              "default": 0,
              "minimum": 0
            },
            "description": "Rows to skip (`<0` is `400 invalid_request`)."
          },
          {
            "name": "search",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "maxLength": 128
            },
            "description": "Literal substring over `merchant_name`/`terminal_name` (`%`, `_` and `!` match themselves)."
          }
        ],
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "`forbidden` — the caller is a merchant-scoped key, not the admin principal.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "404": {
            "description": "`psp_not_found`.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "400": {
            "description": "`invalid_request` — `limit <= 0`, `offset < 0`, `search` longer than 128 characters or a malformed number.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "200": {
            "description": "One page of every live terminal of every template of the PSP; each row also names its `template_id`/`template_name`.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CatalogTerminalListResponse"
                }
              }
            }
          }
        }
      }
    },
    "/v1/meta/ui": {
      "get": {
        "tags": [
          "Admin"
        ],
        "summary": "Build identity of the served admin console",
        "description": "PA-144: `admin_js_sha256` — the first 16 hex characters of the SHA-256 of the `admin.js` bundle EMBEDDED in this binary (the same `include_str!` served at `/admin/static/admin.js`). The value is stable for one deployed bundle and changes with ANY console source edit. `GET /admin` renders it into `<meta name=\"pa-ui-version\">`; the SPA (`js/40-version.js`) compares its own identity with this answer at most every five minutes and on `visibilitychange` and, on a mismatch, shows a NON-DISMISSIBLE «Доступна нова версія консолі — оновіть сторінку» banner with a reload button. There is NO automatic reload: an operator mid-form must not lose typed credentials. Admin-only.",
        "operationId": "getMetaUi",
        "responses": {
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "`forbidden` — the caller is a merchant-scoped key, not the admin principal.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/Problem"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/Internal"
          },
          "200": {
            "description": "The console build identity.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UiVersion"
                }
              }
            },
            "headers": {
              "Cache-Control": {
                "description": "Always `no-store`: a cached build identity would defeat the stale-bundle banner.",
                "schema": {
                  "type": "string",
                  "example": "no-store"
                }
              },
              "ETag": {
                "description": "The build identity itself (`\"<admin_js_sha256>\"`), so a poll may be answered with `304`.",
                "schema": {
                  "type": "string",
                  "example": "\"3f9c1a0d5e7b2468\""
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "description": "Tenant API key (admin, issued at bootstrap/rotation) OR a merchant-scoped API key (PA-72, `mer_sk_…`): the merchant key is limited to its own merchant id on `/v1/merchants/{id}/*` (a foreign id → 404) and has no access to `/v1/merchants` (list) or `/v1/ops/*` (403 forbidden). Keys are stored as SHA-256 hashes only; the raw key is shown exactly once and never logged."
      }
    },
    "parameters": {
      "IdempotencyKey": {
        "name": "Idempotency-Key",
        "in": "header",
        "required": true,
        "schema": {
          "type": "string",
          "minLength": 1,
          "maxLength": 255
        },
        "description": "Client-generated unique key of the operation. A retry with the same key + same body replays the stored result of the original request — the ORIGINAL status code (e.g. `201` for a successful creation) and body, with header `Idempotent-Replayed: true` (a fresh execution answers `false`; no new domain event is written). Same key + different body is a `422 idempotency_key_reuse`; a stored deterministic 4xx problem replays as the same problem. TTL 24h."
      },
      "PaymentId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "type": "string"
        },
        "description": "Payment id (`pay_…`)."
      },
      "InstrumentId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "type": "string"
        },
        "description": "Payment instrument id (`pin_…`)."
      },
      "PayoutId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "type": "string"
        },
        "description": "Payout id (`pout_…`)."
      },
      "MerchantId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "type": "string"
        },
        "description": "Merchant id (`mer_…`)."
      },
      "TenantId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "type": "string"
        },
        "description": "Tenant id (`tn_…`)."
      },
      "DeliveryId": {
        "name": "delivery_id",
        "in": "path",
        "required": true,
        "schema": {
          "type": "integer"
        },
        "description": "Webhook delivery row id (the `delivery_id` of the merchant deliveries log)."
      },
      "ProviderCode": {
        "name": "code",
        "in": "path",
        "required": true,
        "schema": {
          "type": "string"
        },
        "description": "Provider connector code (lowercase identifier, e.g. `payadmit`)."
      }
    },
    "headers": {
      "RetryAfter": {
        "description": "Seconds the client should wait before retrying.",
        "schema": {
          "type": "integer"
        }
      }
    },
    "responses": {
      "Unauthorized": {
        "description": "Missing, invalid or expired bearer key (`unauthorized`) with `WWW-Authenticate: Bearer`",
        "content": {
          "application/problem+json": {
            "schema": {
              "$ref": "#/components/schemas/Problem"
            }
          }
        }
      },
      "BadRequest": {
        "description": "Malformed request (`invalid_request`), e.g. missing idempotency key or unparseable body",
        "content": {
          "application/problem+json": {
            "schema": {
              "$ref": "#/components/schemas/Problem"
            }
          }
        }
      },
      "RateLimited": {
        "description": "Sliding-window limit exceeded (`rate_limited`) with `Retry-After`",
        "headers": {
          "Retry-After": {
            "$ref": "#/components/headers/RetryAfter"
          }
        },
        "content": {
          "application/problem+json": {
            "schema": {
              "$ref": "#/components/schemas/Problem"
            }
          }
        }
      },
      "Internal": {
        "description": "Internal error (`internal`) — the detailed cause goes to the log stream, never to the client",
        "content": {
          "application/problem+json": {
            "schema": {
              "$ref": "#/components/schemas/Problem"
            }
          }
        }
      }
    },
    "schemas": {
      "Problem": {
        "type": "object",
        "description": "RFC 7807 problem report. `type` is always `about:blank`; `code` is the stable PA error code (never a PSP code).",
        "required": [
          "type",
          "title",
          "status",
          "code",
          "message"
        ],
        "properties": {
          "type": {
            "type": "string",
            "description": "RFC 7807 type URI (`about:blank`)."
          },
          "title": {
            "type": "string",
            "example": "Bad Request"
          },
          "status": {
            "type": "integer",
            "description": "HTTP status code repeated in the body.",
            "example": 422
          },
          "code": {
            "type": "string",
            "description": "Stable PA error code: `unauthorized`, `invalid_request`, `idempotency_key_required`, `idempotency_key_reuse`, `idempotency_in_flight`, `unknown_merchant`, `no_eligible_route`, `no_eligible_redirect_route` (PA-81 redirect hosted-page: no `redirect_hpp`-capable target), `wallet_unavailable_for_first_deposit` (PA-126/PA-127: Apple Pay / Google Pay for a payer below the contractual `std_min_deposits` threshold), `payment_not_found`, `invalid_state`, `invalid_state_transition`, `vault_token_already_registered`, `refund_exceeds_amount`, `limit_exceeded`, `rate_limited`, `feature_disabled`, `internal`, …",
            "example": "unknown_merchant"
          },
          "message": {
            "type": "string"
          },
          "payment_id": {
            "type": "string",
            "description": "Set when the error refers to a payment (e.g. idempotency races)."
          },
          "details": {
            "type": "object",
            "additionalProperties": true,
            "description": "RFC 7807 extension members (PA-124): structured context such as `route_target_ids` for `test_mode_shared_mca_conflict`. Absent on ordinary problems."
          }
        }
      },
      "HealthStatus": {
        "type": "object",
        "required": [
          "status"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "ok"
            ]
          }
        }
      },
      "ReadinessStatus": {
        "type": "object",
        "required": [
          "status",
          "checks"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "ready",
              "unavailable"
            ]
          },
          "checks": {
            "type": "object",
            "required": [
              "database"
            ],
            "properties": {
              "database": {
                "type": "string",
                "enum": [
                  "up",
                  "down"
                ]
              }
            }
          }
        }
      },
      "CreatePaymentRequest": {
        "type": "object",
        "required": [
          "merchant_id",
          "amount",
          "currency"
        ],
        "properties": {
          "merchant_id": {
            "type": "string",
            "description": "Merchant of this tenant (`mer_…`). A merchant outside the tenant of the Bearer key → `422 unknown_merchant`."
          },
          "amount": {
            "type": "integer",
            "description": "Positive integer in minor units (cents); `0` or negative → `422 invalid_request`.",
            "minimum": 1,
            "example": 1050
          },
          "currency": {
            "type": "string",
            "description": "ISO 4217 alpha-3. Part of the routing eligibility: when no Route Target of the merchant supports the currency, the payment answers `422 no_eligible_route` without starting an attempt.",
            "example": "EUR"
          },
          "payment_method": {
            "type": "object",
            "required": [
              "type"
            ],
            "description": "Payment method selection — three MUTUALLY EXCLUSIVE families: (1) the saved-card instrument (`instrument_id`, the Secure Fields SDK model), (2) the raw card H2H form (`card`, ADR-0005 model (d) — ONLY for PCI DSS certified merchants after the operator enablement: `422 h2h_not_enabled` otherwise), or (3) a HOSTED (PAN-free) form (`type` = `redirect` | `apple_pay` | `google_pay` | `open_banking` with NO payload fields, PA-81/PA-126 — the player enters the instrument on the PSP's hosted page; routing requires a `redirect_hpp`-capable route target, `422 no_eligible_redirect_route` otherwise). Carrying both card and instrument_id → `422 invalid_request`; carrying card/instrument inside a hosted form → `422 invalid_request`. Each method opens its OWN PSP checkout page (`BASIC_CARD` only cards, `APPLEPAY` only Apple Pay, `GOOGLEPAY` only Google Pay, `OPENBANKING` only open banking) — the wallet button never appears on the card page. Apple Pay / Google Pay are available for RETURNING customers only: with the contractual threshold `std_min_deposits` (PA-127, default 1 = the PA-126 rule) a wallet payment whose customer has fewer SUCCESSFUL deposits than the threshold answers `422 wallet_unavailable_for_first_deposit` BEFORE the idempotency claim (no payment/attempt, no PSP call); `metadata.deposit_stream=redep` is the explicit override. The card values are TRANSIT data: validated, mapped into the processor dispatch and dropped — never persisted, logged, audited or echoed.",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "card",
                  "redirect",
                  "apple_pay",
                  "google_pay",
                  "open_banking"
                ],
                "description": "Payment method type. `card` (saved instrument `instrument_id` or the H2H raw-card form `card`) and the hosted forms `redirect` (PSP card page — PSP `paymentMethod` `BASIC_CARD`), `apple_pay` (`APPLEPAY`), `google_pay` (`GOOGLEPAY`) and `open_banking` (`OPENBANKING`) are supported; any other value → `422 unsupported_payment_method`. A hosted form carries no `card` block and no `instrument_id` (`422 invalid_request`), and the method value is part of the routing eligibility: a Route Target declares its allowed methods in `capabilities.payment_methods` (absent = accepts every method), and a payment no target accepts answers `422 no_eligible_route`. Wallets additionally require the `redep` deposit stream — at least `std_min_deposits` SUCCESSFUL deposits of the customer (PA-127; default 1 = the PA-126 rule) — otherwise `422 wallet_unavailable_for_first_deposit`.",
                "example": "card"
              },
              "instrument_id": {
                "type": "string",
                "description": "PA instrument reference (`pin_…`) from `POST /v1/payment-instruments`. SINGLE-USE: the instrument is consumed (`ACTIVE` → `USED`) atomically with the payment creation, so reusing the same `pin_…` for a second payment → `422 instrument_not_active` (also `unknown_instrument` for an id outside the tenant, `instrument_merchant_mismatch` for another merchant's instrument). Required for the dispatch: without it the connector cannot be called and the attempt ends `FAILED_TECHNICAL`.",
                "example": "pin_01900000-0000-7000-8000-000000000001"
              },
              "card": {
                "type": "object",
                "required": [
                  "card_number",
                  "card_exp_month",
                  "card_exp_year",
                  "card_holder_name",
                  "card_cvc"
                ],
                "description": "H2H raw-card form (ADR-0005 model (d)). Fail-closed gate: accepted only when the deployment flag `PA_H2H_ENABLED` AND the per-merchant `merchants.h2h_enabled` are both true (`422 h2h_not_enabled` otherwise). Validation is fail-fast BEFORE any processor call — an invalid card never leaves PA. PCI: the values live in PA memory for the dispatch only (0 PAN persistence); the payment record stores `payment_method_type: \"card\"` with no instrument.",
                "properties": {
                  "card_number": {
                    "type": "string",
                    "description": "Digits-only PAN, 12-19 digits with a valid Luhn checksum. `422 invalid_card_number` on violation (the message names the constraint, never the value).",
                    "example": "4500000000004454"
                  },
                  "card_exp_month": {
                    "oneOf": [
                      {
                        "type": "integer"
                      },
                      {
                        "type": "string"
                      }
                    ],
                    "description": "Expiry month, 1-12 (number or numeric string). `422 invalid_card_expiry`.",
                    "example": 12
                  },
                  "card_exp_year": {
                    "oneOf": [
                      {
                        "type": "integer"
                      },
                      {
                        "type": "string"
                      }
                    ],
                    "description": "4-digit expiry year (2000-2199); the card is valid through the END of its expiry month. `422 invalid_card_expiry`; already over → `422 card_expired`.",
                    "example": 2029
                  },
                  "card_holder_name": {
                    "type": "string",
                    "description": "Cardholder name, 1-255 characters after trim. `422 invalid_card_holder`.",
                    "example": "John Doe"
                  },
                  "card_cvc": {
                    "type": "string",
                    "description": "CVC, 3-4 digits. `422 invalid_card_cvc`.",
                    "example": "123"
                  }
                }
              }
            }
          },
          "segment": {
            "type": "string",
            "nullable": true,
            "maxLength": 64,
            "pattern": "^[a-z0-9_-]+$",
            "description": "PA-137: the optional ROUTING SEGMENT of the payment — the merchant's traffic label (ADR-0009 §6.4). It selects the SEGMENTED routing cascade of the request's method category; when no cascade carries that segment, the DEFAULT cascade (`segment IS NULL`) answers — an unknown label never turns a configured merchant into a legacy-order merchant. Absent / `null` / blank = the default cascade. Shape: at most 64 characters of `[a-z0-9_-]` (the alphabet of the PSP-callback path segments), `422 invalid_request` otherwise — refused BEFORE the idempotency claim and any PSP call. The value is a routing label, never customer data: it is traced (`routing cascade decision`) and fixed on the attempt (`attempts.routing_segment`), never echoed by the payments API. Part of the idempotency fingerprint when present (an absent field keeps the pre-PA-137 hash, so stored idempotency records keep replaying).",
            "example": "vip-eu"
          },
          "capture_method": {
            "type": "string",
            "enum": [
              "automatic",
              "manual"
            ],
            "default": "automatic",
            "description": "`automatic` (default) — sale model: the PSP dispatch is PURC, so PA `AUTHORIZED` already means the provider captured the money (provider_status `COMPLETED`). `manual` — authorize-only; the capture endpoint is NOT part of the public API surface, and Route Targets are capability-filtered: a target without the manual-capture capability never serves the request (`422 no_eligible_route` when nothing remains; the pilot merchant routes are configured `automatic` only)."
          },
          "customer": {
            "type": "object",
            "description": "Customer context (identity/contact); risk fields belong to `risk_context`. Must be a JSON object (or absent/`null`) — any other JSON type → `422 invalid_request`. FREE-FORM and WRITE-ONLY: the object is stored verbatim and projected to the PSP connector call, but the payment response NEVER echoes it (see `PaymentResponse`; the merchant portal Transaction Details / CSV report are the read surface).",
            "properties": {
              "reference_id": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "number"
                  }
                ],
                "description": "Casino-side player reference (ownership context of the instruments). A JSON number is canonicalized to its decimal form before validation; explicit `null` = absent. Opaque-reference rules: at most 255 characters, charset `[A-Za-z0-9_.@-]`, and a Luhn-valid 13–19 digit run — including a formatted PAN such as `4111-1111-1111-1111` — is rejected as card data (`422 invalid_request`; the message names the constraint, never the value). This is NOT a PAN field.",
                "example": "usr_123"
              },
              "first_name": {
                "type": "string",
                "description": "Player first name; projected into the PSP billing address (required by the Apcopay S2S DEPOSIT profile)."
              },
              "last_name": {
                "type": "string",
                "description": "Player last name; projected into the PSP billing address (required by the Apcopay S2S DEPOSIT profile)."
              },
              "email": {
                "type": "string",
                "description": "Player email; projected to the PSP as the billing/email contact (required by the Apcopay S2S DEPOSIT profile)."
              },
              "phone": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "object"
                  }
                ],
                "description": "Player phone. REQUIRED by the Apcopay S2S DEPOSIT profile — without it the connector rejects the payment with its missing-param error (the fork `IR_04` family). Flat string form: digits only, a leading `+` is stripped (`\"+35712345678\"` → `35712345678`). Structured form `{\"country_code\": \"357\", \"number\": \"12345678\"}` is projected verbatim; `country_code` defaults from the `billing_address` country when absent.",
                "example": "35712345678"
              }
            }
          },
          "risk_context": {
            "type": "object",
            "description": "Casino-supplied risk context (KYC flags, deposit statistics). Free-form, stored with the payment, write-only (never echoed). The MVP routing does not consume it; the connector projection is data-minimized."
          },
          "session_context": {
            "type": "object",
            "description": "Device/session context of the payment. Free-form, stored, write-only (never echoed); it does not affect the MVP routing — EXCEPT the `browser` block, which is projected into the PSP `browser_info` of the dispatch (the Apcopay DirectConnect PURC requires `UserAgent`/`TimeZone`; absent context → the dispatch carries no browser data).",
            "properties": {
              "browser": {
                "type": "object",
                "description": "3DS/browser data collected by the casino client (PAN-free). Keys projected to the PSP: `user_agent`, `accept_header`, `language` (strings), `java_enabled`, `java_script_enabled` (booleans), `screen_width`, `screen_height`, `color_depth` (integers), `time_zone` (JS `getTimezoneOffset()` minutes offset), `ip_address` (must parse as an IP)."
              }
            }
          },
          "billing_address": {
            "type": "object",
            "description": "Billing address; free-form and write-only (never echoed by the payment response). Two consumers: (1) the routing country filter — `country_code`/`country` scopes Route Target selection, and a payment WITHOUT a country never matches a country-filtered target (an all-filtered cascade → `422 no_eligible_route`); (2) the PSP billing projection (`address.line1` etc. — the Apcopay S2S DEPOSIT profile requires `addressLine1`, `city`, `countryCode`, `postalCode`).",
            "properties": {
              "address_line1": {
                "type": "string",
                "description": "Address line 1 (projected to the PSP `line1`; required by the Apcopay S2S DEPOSIT profile)."
              },
              "address_line2": {
                "type": "string",
                "description": "Address line 2 (projected to the PSP `line2`)."
              },
              "city": {
                "type": "string",
                "description": "City (required by the Apcopay S2S DEPOSIT profile)."
              },
              "state": {
                "type": "string",
                "description": "State/region (projected to the PSP `state`)."
              },
              "postal_code": {
                "type": "string",
                "description": "Postal code (projected to the PSP `zip`; required by the Apcopay S2S DEPOSIT profile)."
              },
              "country_code": {
                "type": "string",
                "description": "ISO-2 country code — the routing country-filter input (preferred over `country`)."
              },
              "country": {
                "type": "string",
                "description": "Alternative key of the billing country (read when `country_code` is absent); ISO-2."
              }
            }
          },
          "metadata": {
            "type": "object",
            "description": "Free-form client metadata (e.g. `order_id`); stored with the payment, WRITE-ONLY: never echoed by the payment response. Convention: the external order reference belongs in `metadata.order_reference` — that key surfaces in the merchant portal (Order Reference column, free-text search `q`, CSV report).",
            "additionalProperties": true
          },
          "authentication_type": {
            "type": "string",
            "enum": [
              "three_ds",
              "no_three_ds"
            ],
            "description": "PA-93: the 3DS mode of the H2H raw-card form (payment_method.card) — the PSP runs the 3DS challenge. Default no_three_ds (the exact PA-78 behavior: requests without the field dispatch exactly as before). three_ds: the fork answers requires_customer_action + a typed redirect → PA PENDING + next_action.redirect (the existing projection — no new states). The option belongs to the RAW-CARD form only: on the instrument or redirect form (or without payment_method) it is rejected with 422 invalid_request — never silently ignored. three_ds additionally REQUIRES session_context.browser.ip_address (a parseable IP — the 3DS browser data set; live PA-93 spike: the acquirer rejects the dispatch without Client.IPAddress, so PA fails fast before any dispatch). Participates in the canonical idempotency hash: a replay with the same key must carry the same value."
          },
          "customer_ip": {
            "type": "string",
            "description": "PA-120 (I-8): the payer's client IP for the S2S dispatch `browser_info.ip_address`. The Apcopay live DirectConnect PURC rejects a payment without `Client.IPAddress` (`pspid: 0`, \"Missing Client.IPAddress\" → FAILED_TECHNICAL cascade). Resolution order: `session_context.browser.ip_address` → `customer.ip_address`/`customer.ip` → this field → the socket/X-Forwarded-For peer (only when PA_RATE_LIMIT_TRUST_XFF=1). Validated as IPv4/IPv6; blank is ignored, malformed → `422 invalid_request`. Deliberately NOT part of the idempotency fingerprint: the IP is a dispatch hint, not the payment identity. PA-120 (I-8b): for server-to-server (non-3DS) dispatches the missing `browser_info` fields are completed with the synthetic server-side set (user_agent \"PA/1.0 (server-side H2H)\", accept_header/language/time_zone/color_depth/screen size/java_enabled), because Apcopay also requires the BrowserDetails block (\"Missing BrowserDetails\" otherwise). Explicit session_context.browser values always win; three_ds dispatches never get synthetic data.",
            "example": "203.0.113.7"
          }
        }
      },
      "PaymentResponse": {
        "type": "object",
        "description": "Projection of the logical PA payment — the creation response and `GET /v1/payments/{id}` share it. The request contexts (`customer`, `billing_address`, `metadata`, `risk_context`, `session_context`) are WRITE-ONLY and are NEVER echoed here; the merchant portal (Transaction Details `GET /v1/merchants/{id}/payments/{payment_id}`, CSV report) is the read surface for the merchant's own context. PSP internals stay collapsed: `attempts_summary` is the public projection of the attempt journal.",
        "required": [
          "payment_id",
          "status",
          "amount",
          "currency",
          "capture_method",
          "attempts_summary",
          "created_at"
        ],
        "properties": {
          "payment_id": {
            "type": "string",
            "example": "pay_01900000-0000-7000-8000-00000000000a"
          },
          "status": {
            "type": "string",
            "description": "PA payment status (ADR-0002 §2.2).",
            "enum": [
              "PENDING",
              "AUTHORIZED",
              "CAPTURED",
              "PARTIALLY_REFUNDED",
              "REFUNDED",
              "FAILED",
              "UNKNOWN_PENDING_SYNC"
            ]
          },
          "amount": {
            "type": "integer",
            "example": 1050
          },
          "currency": {
            "type": "string",
            "example": "EUR"
          },
          "capture_method": {
            "type": "string",
            "enum": [
              "automatic",
              "manual"
            ]
          },
          "next_action": {
            "$ref": "#/components/schemas/NextAction"
          },
          "attempts_summary": {
            "type": "array",
            "description": "Collapsed attempt journal: per-attempt sequence number, the public Route Target projection (provider + MID label only, no PSP secrets) and the attempt status. The decline class is NOT part of the summary — it is carried by the full attempt domain model internally, never by this public projection.",
            "items": {
              "type": "object",
              "required": [
                "seq",
                "route_target",
                "status"
              ],
              "properties": {
                "seq": {
                  "type": "integer"
                },
                "route_target": {
                  "type": "object",
                  "description": "Public Route Target projection of the attempt.",
                  "required": [
                    "provider",
                    "mid"
                  ],
                  "properties": {
                    "provider": {
                      "type": "string",
                      "example": "payadmit"
                    },
                    "mid": {
                      "type": "string",
                      "example": "mid_1"
                    }
                  }
                },
                "status": {
                  "type": "string",
                  "enum": [
                    "PENDING",
                    "AUTHORIZED",
                    "DECLINED_SOFT",
                    "DECLINED_HARD",
                    "UNKNOWN",
                    "FAILED_TECHNICAL"
                  ]
                }
              }
            }
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "NextAction": {
        "description": "Typed union (`type` discriminator): what the client should do next. `none` — nothing to do; `wait` carries `retry_after_secs` (synchronize later); `redirect` carries the hosted-page URL (3DS / hosted payment page); `collect_data` asks the client to gather additional data from the player; `approval` marks an operator action (payout gate).",
        "required": [
          "type"
        ],
        "oneOf": [
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "none"
                ]
              }
            }
          },
          {
            "type": "object",
            "required": [
              "retry_after_secs",
              "reason"
            ],
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "wait"
                ]
              },
              "retry_after_secs": {
                "type": "integer"
              },
              "reason": {
                "type": "string"
              }
            }
          },
          {
            "type": "object",
            "required": [
              "redirect_url",
              "method"
            ],
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "redirect"
                ]
              },
              "redirect_url": {
                "type": "string"
              },
              "method": {
                "type": "string"
              }
            }
          },
          {
            "type": "object",
            "required": [
              "required_fields"
            ],
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "collect_data"
                ],
                "description": "Discriminator: the client must collect additional data."
              },
              "required_fields": {
                "type": "array",
                "items": {
                  "type": "string"
                },
                "description": "Field names the processor asked the client to collect from the player (e.g. `email`, `phone`)."
              }
            },
            "description": "The payment processor requests additional data from the player before it can proceed. `required_fields` lists the field names the client must collect (e.g. via the Secure Fields SDK or a follow-up form). After collecting them, create a new payment (or repeat the confirm call) supplying the requested data. In the current live flows the platform answers with `none`, `redirect` or `wait`; `collect_data` is the contract member reserved for processor flows that need extra input."
          },
          {
            "type": "object",
            "required": [
              "resource",
              "allowed_actions"
            ],
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "approval"
                ]
              },
              "resource": {
                "type": "string"
              },
              "allowed_actions": {
                "type": "array",
                "items": {
                  "type": "string"
                }
              }
            }
          }
        ]
      },
      "CreateRefundRequest": {
        "type": "object",
        "required": [
          "payment_id",
          "amount"
        ],
        "properties": {
          "payment_id": {
            "type": "string",
            "example": "pay_01900000-0000-7000-8000-00000000000a"
          },
          "amount": {
            "type": "integer",
            "description": "Minor units; must not exceed the remaining refundable amount.",
            "minimum": 1
          },
          "reason": {
            "type": "string"
          }
        }
      },
      "RefundResponse": {
        "type": "object",
        "required": [
          "refund_id",
          "payment_id",
          "amount",
          "currency",
          "status",
          "payment_status"
        ],
        "properties": {
          "refund_id": {
            "type": "string"
          },
          "payment_id": {
            "type": "string"
          },
          "amount": {
            "type": "integer"
          },
          "currency": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "description": "Refund status.",
            "enum": [
              "PENDING",
              "SUCCEEDED",
              "FAILED"
            ]
          },
          "payment_status": {
            "type": "string",
            "description": "Recomputed payment status.",
            "enum": [
              "AUTHORIZED",
              "CAPTURED",
              "PARTIALLY_REFUNDED",
              "REFUNDED",
              "FAILED"
            ]
          }
        }
      },
      "CreatePaymentInstrumentRequest": {
        "type": "object",
        "required": [
          "merchant_id",
          "vault_token"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "vault_token": {
            "type": "string",
            "description": "Opaque single-use token from the Secure Fields capture surface (credential — never logged, never serialized back)."
          },
          "customer_reference": {
            "type": "string",
            "description": "Casino-side player reference (ownership context; optional)."
          }
        }
      },
      "CardMetaResponse": {
        "type": "object",
        "required": [
          "masked_pan",
          "brand"
        ],
        "properties": {
          "masked_pan": {
            "type": "string",
            "description": "Masked PAN `****<last4>`; PA deliberately does not keep the first digits.",
            "example": "****4242"
          },
          "brand": {
            "type": "string",
            "example": "VISA"
          },
          "exp_month": {
            "type": "string"
          },
          "exp_year": {
            "type": "string"
          }
        }
      },
      "PaymentInstrumentResponse": {
        "type": "object",
        "required": [
          "instrument_id",
          "merchant_id",
          "status",
          "card_meta",
          "created_at"
        ],
        "properties": {
          "instrument_id": {
            "type": "string",
            "example": "pin_01900000-0000-7000-8000-000000000001"
          },
          "merchant_id": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "ACTIVE",
              "USED",
              "EXPIRED",
              "DEACTIVATED",
              "PURGED"
            ]
          },
          "card_meta": {
            "$ref": "#/components/schemas/CardMetaResponse"
          },
          "customer_reference": {
            "type": "string"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "used_at": {
            "type": "string",
            "format": "date-time",
            "description": "First payment usage of the single-use instrument."
          }
        }
      },
      "CreatePayoutRequest": {
        "type": "object",
        "required": [
          "merchant_id",
          "amount",
          "currency",
          "customer_reference"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "amount": {
            "type": "integer",
            "minimum": 1
          },
          "currency": {
            "type": "string"
          },
          "customer_reference": {
            "type": "string",
            "description": "Casino-side player reference."
          },
          "instrument_id": {
            "type": "string",
            "description": "Card-based receiver: PA instrument (`pin_…`); required together with (or replaced by) `receiver`."
          },
          "receiver": {
            "type": "object",
            "description": "Masked receiver metadata; PAN/CVV keys are rejected with `422 invalid_request` (`receiver must not contain card data fields (PAN/CVV)`)."
          },
          "risk_context": {
            "type": "object"
          },
          "retry_of_payout_id": {
            "type": "string",
            "description": "Original payout when retrying after a confirmed DECLINED (a new payout, not a second financial attempt)."
          }
        }
      },
      "PayoutMutationRequest": {
        "type": "object",
        "properties": {
          "reason": {
            "type": "string"
          }
        }
      },
      "PayoutResponse": {
        "type": "object",
        "required": [
          "payout_id",
          "status",
          "amount",
          "currency",
          "customer_reference",
          "attempts_summary",
          "version",
          "created_at"
        ],
        "properties": {
          "payout_id": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "description": "PA payout status (ADR-0004 §4.2 state machine). Phase-1 reachable through this API: `AWAITING_APPROVAL` (manual gate), `APPROVED` (auto-approve policy — decision fixed, PSP dispatch pending), `DECLINED`, `CANCELLED`. `CREATED` is the domain-level initial state (validation and pre-flight limits passed) that a created payout leaves immediately — creation maps it straight onto `AWAITING_APPROVAL` / `APPROVED`. `PROCESSING` and `UNKNOWN_PENDING_SYNC` (as well as `COMPLETED` / `FAILED_TECHNICAL`) become reachable only after the Phase-2 PSP dispatch; `UNKNOWN_PENDING_SYNC` syncs first (ADR-0002 §3 applied to payouts).",
            "enum": [
              "CREATED",
              "AWAITING_APPROVAL",
              "APPROVED",
              "PROCESSING",
              "COMPLETED",
              "DECLINED",
              "FAILED_TECHNICAL",
              "CANCELLED",
              "UNKNOWN_PENDING_SYNC"
            ]
          },
          "amount": {
            "type": "integer"
          },
          "currency": {
            "type": "string"
          },
          "customer_reference": {
            "type": "string"
          },
          "next_action": {
            "$ref": "#/components/schemas/NextAction"
          },
          "attempts_summary": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "seq": {
                  "type": "integer"
                },
                "status": {
                  "type": "string"
                }
              }
            }
          },
          "approval_decisions": {
            "type": "array",
            "description": "Approval-gate decisions (present after a gate mutation).",
            "items": {
              "type": "object",
              "required": [
                "decision",
                "policy_id",
                "actor",
                "role",
                "decided_at"
              ],
              "properties": {
                "decision": {
                  "type": "string",
                  "enum": [
                    "APPROVED",
                    "DECLINED"
                  ]
                },
                "policy_id": {
                  "type": "string"
                },
                "actor": {
                  "type": "string"
                },
                "role": {
                  "type": "string"
                },
                "reason": {
                  "type": "string"
                },
                "snapshot_hash": {
                  "type": "string",
                  "description": "Hash of the immutable policy snapshot the decision was made against."
                },
                "decided_at": {
                  "type": "string",
                  "format": "date-time"
                }
              }
            }
          },
          "version": {
            "type": "integer",
            "description": "Optimistic-concurrency version of the aggregate."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "CreateMerchantRequest": {
        "type": "object",
        "required": [
          "name"
        ],
        "properties": {
          "name": {
            "type": "string",
            "maxLength": 255
          },
          "country": {
            "type": "string",
            "description": "ISO 3166-1 alpha-2."
          },
          "currencies": {
            "type": "array",
            "description": "ISO 4217 alpha-3 codes (default routing currency scope).",
            "items": {
              "type": "string"
            },
            "maxItems": 50
          },
          "legal_entity": {
            "type": "object",
            "description": "Free-form legal entity metadata snapshot."
          },
          "std_min_deposits": {
            "type": "integer",
            "minimum": 1,
            "description": "PA-127: the contractual STD threshold — how many SUCCESSFUL customer deposits (`AUTHORIZED`/`CAPTURED`/`PARTIALLY_REFUNDED`/`REFUNDED`) turn the payer into STD (redep) traffic. Optional; absent = the storage default 1 (the PA-126 rule: first deposit `ftd`, second `redep`). Error split: a non-integer value → `400 invalid_request` (body parse); an INTEGER outside `1..=2147483647` (`< 1` or `> i32::MAX`) → `422 invalid_request`."
          }
        }
      },
      "CreateMerchantResponse": {
        "type": "object",
        "required": [
          "currencies",
          "merchant_id",
          "name",
          "publishable_key"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "country": {
            "type": "string"
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "legal_entity": {
            "type": "object"
          },
          "std_min_deposits": {
            "type": "integer",
            "minimum": 1,
            "description": "PA-127: the contracted STD threshold in force for this merchant (`merchants.std_min_deposits`; default 1 = the PA-126 rule)."
          },
          "publishable_key": {
            "type": "string",
            "description": "PA-48: the derived publishable key of the merchant (`pk_<merchant-uuid>_<digest>`). PUBLIC by design — it lives in the casino frontend and binds browser captures to this merchant; it is not a credential. Deterministic: re-derived on every read (same value as at onboarding)."
          }
        }
      },
      "AddProviderRequest": {
        "type": "object",
        "required": [
          "provider_code",
          "mid",
          "credentials_ref"
        ],
        "properties": {
          "provider_code": {
            "type": "string",
            "description": "Connector code (lowercase identifier, e.g. `payadmit`); normalized to lowercase."
          },
          "mid": {
            "type": "string",
            "description": "Merchant account (MID) label of this provider."
          },
          "credentials_ref": {
            "type": "string",
            "description": "PA-side reference of the connector credentials — the credentials themselves stay in the provider's secret store, never in PA."
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "ISO 4217 alpha-3 codes."
          },
          "countries": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "ISO 3166-1 alpha-2 codes."
          }
        }
      },
      "AddProviderResponse": {
        "type": "object",
        "required": [
          "provider_id",
          "provider_account_id",
          "connector_code",
          "mid_label"
        ],
        "properties": {
          "provider_id": {
            "type": "string"
          },
          "provider_account_id": {
            "type": "string"
          },
          "connector_code": {
            "type": "string"
          },
          "mid_label": {
            "type": "string"
          }
        }
      },
      "AddRouteTargetRequest": {
        "type": "object",
        "required": [
          "provider_account_id",
          "priority"
        ],
        "properties": {
          "provider_account_id": {
            "type": "string",
            "description": "MID (`mid_…`) of a provider OF this merchant."
          },
          "priority": {
            "type": "integer",
            "description": "Cascade order (lower = earlier)."
          },
          "weight": {
            "type": "integer",
            "description": "Weighted split within the same priority (default 1)."
          },
          "filters": {
            "type": "object",
            "description": "Routing filters; a scalar or a list is accepted for each field.",
            "properties": {
              "country": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  }
                ]
              },
              "currency": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  }
                ]
              },
              "method": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  }
                ]
              }
            }
          },
          "capabilities": {
            "type": "object",
            "description": "Capability snapshot of the terminal (e.g. `redirect_hpp`, `s2s_card`, `lookup_by_reference`); absent fields = not declared.",
            "properties": {
              "redirect_hpp": {
                "type": "boolean"
              },
              "s2s_card": {
                "type": "boolean"
              },
              "lookup_by_reference": {
                "type": "boolean"
              },
              "is_test": {
                "type": "boolean",
                "description": "PA-123: Apcopay live/test mode (`true` = sandbox/test, `false` = live). Absent = not declared (pre-PA-123 rows; other connectors). Apcopay Route Targets are created in TEST mode by default; the operator flips it with `PUT /v1/merchants/{id}/route-targets/{rt_id}/test-mode`, which also publishes the flag into the fork MCA metadata."
              }
            }
          }
        }
      },
      "AddRouteTargetResponse": {
        "type": "object",
        "required": [
          "route_target_id",
          "merchant_id",
          "provider_id",
          "provider_account_id",
          "priority",
          "weight",
          "filters",
          "capabilities",
          "status"
        ],
        "properties": {
          "route_target_id": {
            "type": "string"
          },
          "merchant_id": {
            "type": "string"
          },
          "provider_id": {
            "type": "string"
          },
          "provider_account_id": {
            "type": "string"
          },
          "priority": {
            "type": "integer"
          },
          "weight": {
            "type": "integer"
          },
          "status": {
            "$ref": "#/components/schemas/RouteTargetStatus",
            "description": "Lifecycle state (PA-58): a fresh Route Target is always ENABLED."
          },
          "filters": {
            "$ref": "#/components/schemas/RouteTargetFilters"
          },
          "capabilities": {
            "type": "object",
            "properties": {
              "redirect_hpp": {
                "type": "boolean"
              },
              "s2s_card": {
                "type": "boolean"
              },
              "lookup_by_reference": {
                "type": "boolean"
              },
              "is_test": {
                "type": "boolean",
                "description": "PA-123: Apcopay live/test mode (`true` = sandbox/test, `false` = live). Absent = not declared (pre-PA-123 rows; other connectors). Apcopay Route Targets are created in TEST mode by default; the operator flips it with `PUT /v1/merchants/{id}/route-targets/{rt_id}/test-mode`, which also publishes the flag into the fork MCA metadata."
              }
            }
          }
        }
      },
      "RouteTargetTestModeRequest": {
        "type": "object",
        "required": [
          "is_test"
        ],
        "properties": {
          "is_test": {
            "type": "boolean",
            "description": "`true` = test (sandbox) mode, `false` = live mode."
          }
        }
      },
      "RouteTargetTestModeResponse": {
        "type": "object",
        "required": [
          "route_target_id",
          "merchant_id",
          "is_test",
          "previous_is_test",
          "published"
        ],
        "properties": {
          "route_target_id": {
            "type": "string"
          },
          "merchant_id": {
            "type": "string"
          },
          "is_test": {
            "type": "boolean",
            "description": "The effective mode after the call."
          },
          "previous_is_test": {
            "type": "boolean",
            "nullable": true,
            "description": "The mode stored before the call (`null` = undeclared)."
          },
          "published": {
            "type": "boolean",
            "description": "`true` = the fork MCA `metadata` was re-published by THIS call; `false` = idempotent repeat (the stored value was already the requested one)."
          },
          "shared_route_target_ids": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "PA-124: the OTHER route targets of the tenant whose `capabilities.is_test` this call aligned under `force=true`. Absent when nothing was aligned."
          }
        }
      },
      "RouteTargetFilters": {
        "type": "object",
        "required": [
          "countries",
          "currencies",
          "methods"
        ],
        "properties": {
          "countries": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "methods": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "automatic",
                "manual"
              ]
            }
          }
        }
      },
      "ProviderAccountResponse": {
        "type": "object",
        "required": [
          "provider_account_id",
          "mid_label",
          "credentials_ref"
        ],
        "properties": {
          "provider_account_id": {
            "type": "string"
          },
          "mid_label": {
            "type": "string"
          },
          "credentials_ref": {
            "type": "string"
          }
        }
      },
      "ProviderConfigResponse": {
        "type": "object",
        "required": [
          "provider_id",
          "connector_code",
          "display_name",
          "currencies",
          "countries",
          "accounts"
        ],
        "properties": {
          "provider_id": {
            "type": "string"
          },
          "connector_code": {
            "type": "string"
          },
          "display_name": {
            "type": "string"
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "countries": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "accounts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProviderAccountResponse"
            }
          }
        }
      },
      "RouteTargetConfigResponse": {
        "type": "object",
        "required": [
          "route_target_id",
          "provider_id",
          "provider_account_id",
          "priority",
          "weight",
          "active",
          "filters",
          "capabilities",
          "status"
        ],
        "properties": {
          "route_target_id": {
            "type": "string"
          },
          "provider_id": {
            "type": "string"
          },
          "provider_account_id": {
            "type": "string"
          },
          "priority": {
            "type": "integer"
          },
          "weight": {
            "type": "integer"
          },
          "status": {
            "$ref": "#/components/schemas/RouteTargetStatus",
            "description": "Lifecycle state (PA-58, PA-55 §8). Source of truth for routing eligibility; the legacy `active` flag is its derived projection."
          },
          "active": {
            "type": "boolean"
          },
          "filters": {
            "$ref": "#/components/schemas/RouteTargetFilters"
          },
          "capabilities": {
            "type": "object",
            "description": "Capability snapshot; absent fields = not declared.",
            "properties": {
              "redirect_hpp": {
                "type": "boolean"
              },
              "s2s_card": {
                "type": "boolean"
              },
              "lookup_by_reference": {
                "type": "boolean"
              },
              "is_test": {
                "type": "boolean",
                "description": "PA-123: Apcopay live/test mode (`true` = sandbox/test, `false` = live). Absent = not declared (pre-PA-123 rows; other connectors). Apcopay Route Targets are created in TEST mode by default; the operator flips it with `PUT /v1/merchants/{id}/route-targets/{rt_id}/test-mode`, which also publishes the flag into the fork MCA metadata."
              }
            }
          }
        }
      },
      "MerchantConfigResponse": {
        "type": "object",
        "required": [
          "created_at",
          "currencies",
          "merchant_id",
          "name",
          "providers",
          "publishable_key",
          "route_targets"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "country": {
            "type": "string"
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "legal_entity": {
            "type": "object"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "providers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProviderConfigResponse"
            }
          },
          "route_targets": {
            "type": "array",
            "items": {
              "type": "object",
              "required": [
                "route_target_id",
                "provider_id",
                "provider_account_id",
                "priority",
                "weight",
                "active",
                "filters",
                "capabilities"
              ],
              "properties": {
                "route_target_id": {
                  "type": "string"
                },
                "provider_id": {
                  "type": "string"
                },
                "provider_account_id": {
                  "type": "string"
                },
                "priority": {
                  "type": "integer"
                },
                "weight": {
                  "type": "integer"
                },
                "active": {
                  "type": "boolean"
                },
                "filters": {
                  "$ref": "#/components/schemas/RouteTargetFilters"
                },
                "capabilities": {
                  "type": "object",
                  "properties": {
                    "redirect_hpp": {
                      "type": "boolean"
                    },
                    "s2s_card": {
                      "type": "boolean"
                    },
                    "lookup_by_reference": {
                      "type": "boolean"
                    }
                  }
                }
              }
            }
          },
          "webhook_url": {
            "type": "string",
            "description": "Registered webhook endpoint (URL only — the signing secret is never returned by a read)."
          },
          "publishable_key": {
            "type": "string",
            "description": "PA-48: the derived publishable key of the merchant (`pk_<merchant-uuid>_<digest>`). PUBLIC by design — it lives in the casino frontend and binds browser captures to this merchant; it is not a credential. Deterministic: re-derived on every read (same value as at onboarding)."
          },
          "payout_self_approval": {
            "type": "boolean",
            "description": "PA-107: merchant payout SELF-approval flag — the operator-facing read of the toggle (`PUT /v1/merchants/{id}/payout-self-approval`); `true` = the merchant may approve/decline its own `AWAITING_APPROVAL` payouts through `/portal`. Fail-closed default `false` (the operator four-eyes gate)."
          },
          "std_min_deposits": {
            "type": "integer",
            "minimum": 1,
            "description": "PA-127: the contractual STD threshold — how many SUCCESSFUL customer deposits move the payer to STD (redep) traffic (`PUT /v1/merchants/{id}/std-min-deposits`; default 1 = the PA-126 rule)."
          }
        }
      },
      "SetMerchantWebhookRequest": {
        "type": "object",
        "required": [
          "url"
        ],
        "properties": {
          "url": {
            "type": "string",
            "maxLength": 2048,
            "description": "HTTP(S) endpoint of the merchant backend that receives signed payment events."
          }
        }
      },
      "SetMerchantWebhookResponse": {
        "type": "object",
        "required": [
          "merchant_id",
          "webhook_url",
          "webhook_secret"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "webhook_url": {
            "type": "string"
          },
          "webhook_secret": {
            "type": "string",
            "description": "HMAC signing secret (`whs_…`) — shown EXACTLY ONCE in this response, never surfaced again, never logged. Verify `PA-Webhook-Signature: v1=<hex(HMAC-SHA256(raw_body, secret))>` over the raw delivered bytes."
          }
        }
      },
      "WebhookDeliveryListResponse": {
        "type": "object",
        "required": [
          "count",
          "deliveries"
        ],
        "properties": {
          "payment_id": {
            "type": "string",
            "description": "The payment the log belongs to (payment-scoped read)."
          },
          "payout_id": {
            "type": "string",
            "description": "The payout the log belongs to (payout-scoped read, PA-114)."
          },
          "count": {
            "type": "integer"
          },
          "deliveries": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/WebhookDeliveryResponse"
            }
          }
        },
        "description": "Delivery history of one webhook-scoped entity (payment or payout), oldest event first. Exactly one of `payment_id` / `payout_id` is set."
      },
      "WebhookDeliveryResponse": {
        "type": "object",
        "description": "One webhook delivery of the outbox history. Delivery is asynchronous and at-least-once: PENDING → (retries with exponential backoff) → DELIVERED on the first 2xx, DEAD after the attempt budget.",
        "required": [
          "event_id",
          "event_type",
          "status",
          "attempts",
          "created_at"
        ],
        "properties": {
          "event_id": {
            "type": "string",
            "description": "Unique event id — the receiver-side dedup key (`PA-Event-Id` header)."
          },
          "event_type": {
            "type": "string",
            "enum": [
              "payment.authorized",
              "payment.captured",
              "payment.refunded",
              "payment.failed"
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "PENDING",
              "DELIVERED",
              "DEAD"
            ]
          },
          "attempts": {
            "type": "integer"
          },
          "last_error": {
            "type": "string",
            "description": "Stable error class of the last failed attempt (`timeout`, `connect`, `status:<HTTP-код>`); absent after a successful delivery."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "delivered_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "AuditListResponse": {
        "type": "object",
        "required": [
          "events",
          "count"
        ],
        "properties": {
          "count": {
            "type": "integer"
          },
          "events": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AuditEventResponse"
            }
          }
        }
      },
      "AuditEventResponse": {
        "type": "object",
        "required": [
          "id",
          "created_at",
          "actor",
          "action",
          "entity_type",
          "entity_id"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "description": "Monotonic audit id."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "actor": {
            "type": "string",
            "description": "Authenticated principal (`tenant:<uuid>`); raw keys are never recorded."
          },
          "action": {
            "type": "string",
            "description": "Closed registry code (`create_merchant`, `update_routing`, `rotate_key`, …)."
          },
          "entity_type": {
            "type": "string"
          },
          "entity_id": {
            "type": "string"
          },
          "details": {
            "type": "object",
            "description": "Structured context of the change; credentials are never part of it."
          }
        }
      },
      "RotateKeyResponse": {
        "type": "object",
        "required": [
          "new_key",
          "old_key_expires_at",
          "key_id"
        ],
        "properties": {
          "new_key": {
            "type": "string",
            "description": "Raw tenant API key — valid immediately, shown EXACTLY ONCE, stored only as a SHA-256 hash."
          },
          "old_key_expires_at": {
            "type": "string",
            "format": "date-time",
            "description": "End of the 24h grace period of the replaced key."
          },
          "key_id": {
            "type": "string",
            "description": "Id of the new key (for `DELETE /v1/tenants/{id}/keys/{key_id}`)."
          }
        }
      },
      "RouteTargetStatus": {
        "type": "string",
        "description": "Lifecycle state of a Route Target (PA-58, PA-55 §8).",
        "enum": [
          "ENABLED",
          "DRAINING",
          "DEGRADED",
          "DISABLED"
        ]
      },
      "RouteTargetStatusChangeRequest": {
        "type": "object",
        "required": [
          "status"
        ],
        "properties": {
          "status": {
            "$ref": "#/components/schemas/RouteTargetStatus"
          }
        }
      },
      "MerchantStateCount": {
        "type": "object",
        "description": "One state of the window histogram (the full registry is always present, zero-filled).",
        "required": [
          "state",
          "count"
        ],
        "properties": {
          "state": {
            "type": "string",
            "enum": [
              "PENDING",
              "AUTHORIZED",
              "CAPTURED",
              "PARTIALLY_REFUNDED",
              "REFUNDED",
              "FAILED",
              "UNKNOWN_PENDING_SYNC"
            ]
          },
          "count": {
            "type": "integer",
            "description": "Payments of the window in this state."
          }
        }
      },
      "MerchantDailyStateAmount": {
        "type": "object",
        "description": "Per-state amount of one daily rollup row (full registry, zero-filled; minor units).",
        "required": [
          "state",
          "amount_minor"
        ],
        "properties": {
          "state": {
            "type": "string",
            "enum": [
              "PENDING",
              "AUTHORIZED",
              "CAPTURED",
              "PARTIALLY_REFUNDED",
              "REFUNDED",
              "FAILED",
              "UNKNOWN_PENDING_SYNC"
            ]
          },
          "amount_minor": {
            "type": "integer",
            "description": "Sum of amounts in this state on that day, minor units."
          }
        }
      },
      "MerchantDailySummary": {
        "type": "object",
        "description": "One (UTC day, currency) row of the daily rollup — the Reconciliation view. Amounts stay per-currency (never mixed).",
        "required": [
          "date",
          "currency",
          "count",
          "total_amount_minor",
          "by_state"
        ],
        "properties": {
          "date": {
            "type": "string",
            "description": "UTC calendar day, `YYYY-MM-DD`.",
            "example": "2025-09-24"
          },
          "currency": {
            "type": "string",
            "example": "EUR"
          },
          "count": {
            "type": "integer",
            "description": "All payments of the day+currency (any state)."
          },
          "total_amount_minor": {
            "type": "integer",
            "description": "Sum of all payments of the day+currency, minor units."
          },
          "by_state": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MerchantDailyStateAmount"
            }
          }
        }
      },
      "MerchantCurrencyAmount": {
        "type": "object",
        "description": "Turnover volume of one currency within the window (minor units).",
        "required": [
          "currency",
          "amount_minor"
        ],
        "properties": {
          "currency": {
            "type": "string",
            "example": "EUR"
          },
          "amount_minor": {
            "type": "integer",
            "description": "Sum of `AUTHORIZED | CAPTURED` amounts in this currency, minor units."
          }
        }
      },
      "MerchantPaymentMethodShare": {
        "type": "object",
        "description": "One payment option of the distribution card: count of the window payments with this `payment_method_type` (currently `card`).",
        "required": [
          "method",
          "count",
          "volume_minor"
        ],
        "properties": {
          "method": {
            "type": "string",
            "example": "card"
          },
          "count": {
            "type": "integer",
            "description": "Window payments of this payment option."
          },
          "volume_minor": {
            "type": "integer",
            "description": "Volume of the approved payments of this option, minor units."
          }
        }
      },
      "MerchantStatsResponse": {
        "type": "object",
        "description": "Dashboard snapshot of the merchant portal (Turnover EUR with previous-period delta, Approval Ratio, Transaction Count, Pay Ins, Credits/Refunds, Payment Option Distribution, state histogram, daily rollup).",
        "required": [
          "merchant_id",
          "window",
          "window_days",
          "turnover_eur",
          "previous_turnover_eur",
          "approval_ratio",
          "transaction_count",
          "approved_count",
          "failed_count",
          "payins",
          "refunds_count",
          "refunds_eur",
          "by_state",
          "turnover_by_currency",
          "payment_method_distribution",
          "daily",
          "generated_at",
          "deposits_eur",
          "previous_deposits_eur"
        ],
        "properties": {
          "merchant_id": {
            "type": "string",
            "example": "mer_01900000-0000-7000-8000-00000000000a"
          },
          "window": {
            "type": "string",
            "enum": [
              "7d",
              "30d"
            ],
            "description": "Echoed window value."
          },
          "window_days": {
            "type": "integer",
            "enum": [
              7,
              30
            ],
            "description": "Window length in days."
          },
          "turnover_eur": {
            "type": "integer",
            "description": "Turnover EUR: `AUTHORIZED | CAPTURED` volume in EUR, MINOR units (cents). Money IN — refunded volume is reported as Credits/Refunds, not turnover.",
            "example": 3050
          },
          "previous_turnover_eur": {
            "type": "integer",
            "description": "Same turnover aggregate over the PREVIOUS period of the same length (`[now-2N, now-N)`) — the 'Previously' line of the Turnover card.",
            "example": 0
          },
          "approval_ratio": {
            "type": "number",
            "format": "double",
            "description": "Approved / (approved + FAILED) payments of the window, percent 0-100, two decimals — the apcopay formula `authorized / (authorized + declined + failed)`. In-flight states (`PENDING`, `UNKNOWN_PENDING_SYNC`) stay out of the denominator; an undecided window answers 0.",
            "example": 75.0
          },
          "transaction_count": {
            "type": "integer",
            "description": "All payments of the window (any state).",
            "example": 4
          },
          "approved_count": {
            "type": "integer",
            "description": "Approved-family payments of the window (the ratio numerator).",
            "example": 3
          },
          "failed_count": {
            "type": "integer",
            "description": "FAILED payments of the window (the ratio decline side).",
            "example": 1
          },
          "payins": {
            "type": "integer",
            "description": "Pay Ins: count of `AUTHORIZED | CAPTURED` payments (successful deposits).",
            "example": 3
          },
          "deposits_eur": {
            "type": "integer",
            "description": "Deposits €-line: `AUTHORIZED | CAPTURED` volume in EUR, minor units — the money confirmed IN of the Deposits card.",
            "example": 3050
          },
          "previous_deposits_eur": {
            "type": "integer",
            "description": "Deposits €-line of the PREVIOUS period (the delta basis of the Deposits card).",
            "example": 0
          },
          "refunds_count": {
            "type": "integer",
            "description": "Credits/Refunds: count of SUCCEEDED refunds (any currency).",
            "example": 0
          },
          "refunds_eur": {
            "type": "integer",
            "description": "Credits/Refunds: sum of SUCCEEDED refunds in EUR, minor units.",
            "example": 0
          },
          "by_state": {
            "type": "array",
            "description": "Full state registry of the window, zero-filled.",
            "items": {
              "$ref": "#/components/schemas/MerchantStateCount"
            }
          },
          "turnover_by_currency": {
            "type": "array",
            "description": "Turnover volume per currency (minor units) — the honest companion of the EUR-only turnover card.",
            "items": {
              "$ref": "#/components/schemas/MerchantCurrencyAmount"
            }
          },
          "payment_method_distribution": {
            "type": "array",
            "description": "Payment Option Distribution of the window (per `payment_method_type`, count only).",
            "items": {
              "$ref": "#/components/schemas/MerchantPaymentMethodShare"
            }
          },
          "daily": {
            "type": "array",
            "description": "Daily rollup of the window (UTC days, per currency) — the Reconciliation view.",
            "items": {
              "$ref": "#/components/schemas/MerchantDailySummary"
            }
          },
          "generated_at": {
            "type": "string",
            "description": "RFC 3339 moment the snapshot was computed."
          }
        }
      },
      "MerchantCardMeta": {
        "type": "object",
        "description": "Masked instrument metadata of a payment (PA-13 projection — no PAN segments, no CVV, no holder name).",
        "required": [
          "brand",
          "last4"
        ],
        "properties": {
          "brand": {
            "type": "string",
            "example": "VISA"
          },
          "last4": {
            "type": "string",
            "example": "4242"
          },
          "exp_month": {
            "type": "string",
            "example": "08"
          },
          "exp_year": {
            "type": "string",
            "example": "2028"
          }
        }
      },
      "MerchantPaymentSummary": {
        "type": "object",
        "description": "One payment of the merchant portal Transactions grid (apcopay layout — summary projection with PSP and method columns; no attempt journal).",
        "required": [
          "payment_id",
          "status",
          "amount",
          "currency",
          "created_at",
          "payment_method_type"
        ],
        "properties": {
          "payment_id": {
            "type": "string",
            "example": "pay_01900000-0000-7000-8000-00000000000a"
          },
          "status": {
            "type": "string",
            "enum": [
              "PENDING",
              "AUTHORIZED",
              "CAPTURED",
              "PARTIALLY_REFUNDED",
              "REFUNDED",
              "FAILED",
              "UNKNOWN_PENDING_SYNC"
            ]
          },
          "amount": {
            "type": "integer",
            "description": "Minor units of `currency`.",
            "example": 1050
          },
          "currency": {
            "type": "string",
            "example": "EUR"
          },
          "created_at": {
            "type": "string",
            "description": "RFC 3339."
          },
          "provider": {
            "type": "string",
            "description": "Latest attempt's connector code (`payadmit`, …); absent without attempts.",
            "example": "payadmit"
          },
          "psp_reference": {
            "type": "string",
            "description": "Latest attempt's PSP transaction reference; absent without attempts.",
            "example": "mock-txn"
          },
          "error_code": {
            "type": "string",
            "description": "Latest attempt's PSP decline/response code (the verbatim Error Code column); absent when the attempt carries none.",
            "example": "do_not_honor"
          },
          "payment_method_type": {
            "type": "string",
            "example": "card"
          },
          "card": {
            "$ref": "#/components/schemas/MerchantCardMeta"
          },
          "order_reference": {
            "type": "string",
            "description": "Best-effort merchant context from the free-form request metadata (`order_reference`)."
          },
          "email": {
            "type": "string",
            "description": "Best-effort player contact from the request customer object."
          }
        }
      },
      "MerchantPaymentListResponse": {
        "type": "object",
        "description": "Payments page of the merchant portal (newest first).",
        "required": [
          "merchant_id",
          "total",
          "limit",
          "offset",
          "count",
          "payments"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "PENDING",
              "AUTHORIZED",
              "CAPTURED",
              "PARTIALLY_REFUNDED",
              "REFUNDED",
              "FAILED",
              "UNKNOWN_PENDING_SYNC"
            ],
            "description": "Echoed status filter (absent when unfiltered)."
          },
          "total": {
            "type": "integer",
            "description": "Total payments matching the filter, independent of the page."
          },
          "limit": {
            "type": "integer"
          },
          "offset": {
            "type": "integer"
          },
          "count": {
            "type": "integer",
            "description": "Rows on this page."
          },
          "payments": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MerchantPaymentSummary"
            }
          }
        }
      },
      "MerchantAttemptDetail": {
        "type": "object",
        "description": "One attempt of the details view: the public summary fields PLUS the forensic provider facts of the merchant's own payment (provider status / code / transaction reference) — the collapse of the public payments API does not bind this merchant-scoped read.",
        "required": [
          "seq",
          "provider",
          "mid",
          "status",
          "started_at"
        ],
        "properties": {
          "seq": {
            "type": "integer"
          },
          "provider": {
            "type": "string",
            "description": "Connector code of the Route Target snapshot.",
            "example": "payadmit"
          },
          "mid": {
            "type": "string",
            "description": "MID label of the Route Target snapshot.",
            "example": "mid_portal"
          },
          "status": {
            "type": "string",
            "enum": [
              "PENDING",
              "AUTHORIZED",
              "DECLINED_SOFT",
              "DECLINED_HARD",
              "UNKNOWN",
              "FAILED_TECHNICAL"
            ]
          },
          "provider_status": {
            "type": "string",
            "description": "Normalized PSP status, when present."
          },
          "provider_code": {
            "type": "string",
            "description": "Raw PSP response code, when present."
          },
          "provider_transaction_id": {
            "type": "string",
            "description": "PSP transaction reference, when present."
          },
          "started_at": {
            "type": "string",
            "description": "RFC 3339."
          },
          "finished_at": {
            "type": "string",
            "description": "RFC 3339; present for finished attempts."
          }
        }
      },
      "MerchantRefundSummary": {
        "type": "object",
        "description": "One related refund of the details view (Related Transactions).",
        "required": [
          "refund_id",
          "amount",
          "currency",
          "status",
          "created_at"
        ],
        "properties": {
          "refund_id": {
            "type": "string",
            "example": "ref_01900000-0000-7000-8000-00000000000a"
          },
          "amount": {
            "type": "integer",
            "description": "Minor units of `currency`.",
            "example": 500
          },
          "currency": {
            "type": "string",
            "example": "EUR"
          },
          "status": {
            "type": "string",
            "enum": [
              "PENDING",
              "SUCCEEDED",
              "FAILED"
            ]
          },
          "created_at": {
            "type": "string",
            "description": "RFC 3339."
          }
        }
      },
      "MerchantPaymentDetailsResponse": {
        "type": "object",
        "description": "Transaction Details view of the merchant portal: grid summary + PSP details (attempt journal with the forensic provider facts) + related refunds + the free-form request objects.",
        "required": [
          "merchant_id",
          "payment_id",
          "status",
          "amount",
          "currency",
          "capture_method",
          "payment_method_type",
          "correlation_id",
          "created_at",
          "updated_at",
          "attempts",
          "refunds"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "payment_id": {
            "type": "string",
            "example": "pay_01900000-0000-7000-8000-00000000000a"
          },
          "status": {
            "type": "string",
            "enum": [
              "PENDING",
              "AUTHORIZED",
              "CAPTURED",
              "PARTIALLY_REFUNDED",
              "REFUNDED",
              "FAILED",
              "UNKNOWN_PENDING_SYNC"
            ]
          },
          "amount": {
            "type": "integer",
            "description": "Minor units of `currency`.",
            "example": 1050
          },
          "currency": {
            "type": "string",
            "example": "EUR"
          },
          "capture_method": {
            "type": "string",
            "enum": [
              "automatic",
              "manual"
            ]
          },
          "payment_method_type": {
            "type": "string",
            "example": "card"
          },
          "provider": {
            "type": "string",
            "description": "Latest attempt's connector code; absent without attempts.",
            "example": "payadmit"
          },
          "psp_reference": {
            "type": "string",
            "description": "Latest attempt's PSP transaction reference; absent without attempts."
          },
          "error_code": {
            "type": "string",
            "description": "Latest attempt's PSP decline/response code (the verbatim Error Code of the Transactions grid); absent when the attempt carries none."
          },
          "card": {
            "$ref": "#/components/schemas/MerchantCardMeta"
          },
          "order_reference": {
            "type": "string",
            "description": "Best-effort merchant context from the request metadata."
          },
          "email": {
            "type": "string",
            "description": "Best-effort player contact from the request customer."
          },
          "correlation_id": {
            "type": "string",
            "description": "Correlation id shared with the PA trace of the payment creation."
          },
          "next_action": {
            "$ref": "#/components/schemas/NextAction",
            "description": "Typed next action of the payment (PA-89): the `redirect` variant carries the hosted PSP page URL behind the portal's «Платёжная страница» block. Absent when there is nothing to do."
          },
          "metadata": {
            "type": "object",
            "description": "The merchant's free-form request metadata (verbatim)."
          },
          "customer": {
            "type": "object",
            "description": "The merchant's free-form customer object (verbatim)."
          },
          "created_at": {
            "type": "string",
            "description": "RFC 3339."
          },
          "updated_at": {
            "type": "string",
            "description": "RFC 3339."
          },
          "attempts": {
            "type": "array",
            "description": "Attempt journal, oldest first (the Events timeline + PSP details).",
            "items": {
              "$ref": "#/components/schemas/MerchantAttemptDetail"
            }
          },
          "refunds": {
            "type": "array",
            "description": "Related refunds, oldest first (Related Transactions).",
            "items": {
              "$ref": "#/components/schemas/MerchantRefundSummary"
            }
          }
        }
      },
      "MerchantWebhookDeliveryResponse": {
        "type": "object",
        "description": "One delivery of the merchant webhook health view (same projection discipline as WebhookDeliveryResponse — the payload is never projected).",
        "required": [
          "delivery_id",
          "event_id",
          "event_type",
          "status",
          "attempts",
          "created_at"
        ],
        "properties": {
          "delivery_id": {
            "type": "integer",
            "description": "Delivery row id — the manual re-delivery target (PA-86): POST /v1/merchants/{id}/webhooks/deliveries/{delivery_id}/retry re-queues PENDING/DEAD deliveries."
          },
          "event_id": {
            "type": "string",
            "description": "Receiver-side dedup key (UUIDv7)."
          },
          "event_type": {
            "type": "string",
            "enum": [
              "payment.authorized",
              "payment.captured",
              "payment.refunded",
              "payment.failed",
              "payout.approved",
              "payout.completed",
              "payout.declined",
              "payout.cancelled"
            ]
          },
          "payment_id": {
            "type": "string",
            "example": "pay_01900000-0000-7000-8000-00000000000a",
            "description": "The owning payment of the delivery (payment events only)."
          },
          "payout_id": {
            "type": "string",
            "example": "po_01900000-0000-7000-8000-00000000000a",
            "description": "The owning payout of the delivery (payout events, PA-114)."
          },
          "status": {
            "type": "string",
            "enum": [
              "PENDING",
              "DELIVERED",
              "DEAD"
            ]
          },
          "attempts": {
            "type": "integer",
            "description": "Delivery attempts made so far."
          },
          "last_error": {
            "type": "string",
            "description": "Last error class (`timeout`, `connect`, `status:<HTTP-код>`); absent after a success."
          },
          "created_at": {
            "type": "string",
            "description": "RFC 3339."
          },
          "delivered_at": {
            "type": "string",
            "description": "RFC 3339; present when DELIVERED."
          },
          "target_url": {
            "type": "string",
            "description": "PA-149: WHERE this row was dispatched — present only for a manual one-off re-send. Masked projection: scheme + host + path, the query string replaced by `?***` (it may carry a receiver secret). Absent for an original delivery (it goes to the merchant's registered endpoint).",
            "example": "https://receiver.example.org/pa/webhook?***"
          },
          "resend_of": {
            "type": "integer",
            "description": "PA-149: the delivery row this one re-sends; absent for an original emission.",
            "example": 4211
          }
        }
      },
      "MerchantWebhookDeliveryListResponse": {
        "type": "object",
        "description": "The deliveries of ALL payments and payouts (PA-114) of the merchant, newest first. PA-149: a PAGINATED and FILTERABLE page — `count` is the size of THIS page, `total` the number of rows matching the filter (the journal's «1–25 з N» counter), `limit`/`offset` the effective window. Delivery is at-least-once; receivers verify the HMAC signature on their side (this log carries the PA-side delivery health only).",
        "required": [
          "merchant_id",
          "count",
          "total",
          "limit",
          "offset",
          "deliveries"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "payment_id": {
            "type": "string",
            "description": "Echoed payment filter (absent when unfiltered)."
          },
          "count": {
            "type": "integer",
            "description": "Rows on this page."
          },
          "total": {
            "type": "integer",
            "description": "PA-149: how many rows match the filter (not just this page).",
            "example": 187
          },
          "limit": {
            "type": "integer",
            "description": "PA-149: the effective page size (echo of the clamped request).",
            "example": 25
          },
          "offset": {
            "type": "integer",
            "description": "PA-149: the effective page offset (echo of the request).",
            "example": 0
          },
          "deliveries": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MerchantWebhookDeliveryResponse"
            }
          }
        }
      },
      "RouteTargetStatusChangeResponse": {
        "type": "object",
        "required": [
          "route_target_id",
          "merchant_id",
          "previous_status",
          "status",
          "active"
        ],
        "properties": {
          "route_target_id": {
            "type": "string",
            "description": "Public identifier of the changed Route Target (`rt_...`)."
          },
          "merchant_id": {
            "type": "string"
          },
          "previous_status": {
            "$ref": "#/components/schemas/RouteTargetStatus"
          },
          "status": {
            "$ref": "#/components/schemas/RouteTargetStatus"
          },
          "active": {
            "type": "boolean",
            "description": "Legacy traffic projection of the NEW state (ENABLED/DEGRADED → true; DRAINING/DISABLED → false)."
          }
        }
      },
      "UpdateWebhookUrlRequest": {
        "type": "object",
        "required": [
          "url"
        ],
        "properties": {
          "url": {
            "type": "string",
            "maxLength": 2048,
            "description": "New HTTPS endpoint of the casino backend receiving signed events (plain http is not accepted for self-service)."
          }
        }
      },
      "UpdateWebhookUrlResponse": {
        "type": "object",
        "required": [
          "merchant_id",
          "webhook_url"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "webhook_url": {
            "type": "string",
            "description": "The new endpoint; the signing secret is unchanged."
          }
        }
      },
      "RotateWebhookSecretResponse": {
        "type": "object",
        "required": [
          "merchant_id",
          "webhook_url",
          "webhook_secret",
          "old_secret_expires_at",
          "rotated_at"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "webhook_url": {
            "type": "string"
          },
          "webhook_secret": {
            "type": "string",
            "description": "The NEW active HMAC signing secret (`whs_…`) — shown EXACTLY ONCE, never surfaced again, never logged. From now on deliveries are signed with it immediately."
          },
          "old_secret_expires_at": {
            "type": "string",
            "description": "RFC 3339 end of the receiver-side grace window of the replaced secret: verify BOTH secrets until it (dual-verify), only the new one after."
          },
          "rotated_at": {
            "type": "string",
            "description": "RFC 3339 rotation time."
          }
        }
      },
      "WebhookSecretStatus": {
        "type": "string",
        "enum": [
          "issued",
          "never_shown"
        ],
        "description": "PA-13 once-semantics marker: `issued` = a webhook (URL+secret) is registered — the secret was shown exactly once and is never returned by a read; `never_shown` = no webhook registered yet."
      },
      "MerchantBaseUrls": {
        "type": "object",
        "required": [
          "production",
          "sandbox"
        ],
        "properties": {
          "production": {
            "type": "string",
            "description": "Production API base URL (PA-64 domain)."
          },
          "sandbox": {
            "type": "string",
            "description": "Sandbox stand base URL."
          }
        }
      },
      "ApcopayTestCard": {
        "type": "object",
        "required": [
          "number",
          "expiry",
          "holder"
        ],
        "properties": {
          "number": {
            "type": "string",
            "description": "PAN of the sandbox terminal card (public fixture)."
          },
          "expiry": {
            "type": "string"
          },
          "holder": {
            "type": "string"
          }
        }
      },
      "PayadmitTestCard": {
        "type": "object",
        "required": [
          "number",
          "expiry",
          "cvc"
        ],
        "properties": {
          "number": {
            "type": "string",
            "description": "PAN of the sandbox terminal card (public fixture)."
          },
          "expiry": {
            "type": "string"
          },
          "cvc": {
            "type": "string"
          }
        }
      },
      "MerchantTestCards": {
        "type": "object",
        "required": [
          "apcopay",
          "payadmit"
        ],
        "properties": {
          "apcopay": {
            "$ref": "#/components/schemas/ApcopayTestCard"
          },
          "payadmit": {
            "$ref": "#/components/schemas/PayadmitTestCard"
          }
        }
      },
      "MerchantSelfProfileProvider": {
        "type": "object",
        "required": [
          "connector_code",
          "mid_label",
          "currencies",
          "status"
        ],
        "properties": {
          "connector_code": {
            "type": "string",
            "description": "Connector code of the linked PSP (`apcopay`, `payadmit`, …)."
          },
          "mid_label": {
            "type": "string",
            "description": "MID label of the linked account."
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Currency scope of the connector (ISO 4217 alpha-3)."
          },
          "status": {
            "type": "string",
            "description": "Connector lifecycle status (PA-55 §8): `ENABLED | DEPRECATED | RETIRED`."
          }
        }
      },
      "MerchantSelfProfileResponse": {
        "type": "object",
        "required": [
          "merchant_id",
          "name",
          "api_key",
          "base_urls",
          "webhook_secret_status",
          "providers",
          "test_cards"
        ],
        "properties": {
          "merchant_id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "api_key": {
            "type": "string",
            "description": "The bearer key of THIS request (single-principal MVP echo). Never logged, never persisted by PA."
          },
          "base_urls": {
            "$ref": "#/components/schemas/MerchantBaseUrls"
          },
          "webhook_url": {
            "type": "string",
            "nullable": true,
            "description": "Registered webhook endpoint; `null` when none (then `webhook_secret_status` is `never_shown`)."
          },
          "webhook_secret_status": {
            "$ref": "#/components/schemas/WebhookSecretStatus"
          },
          "providers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MerchantSelfProfileProvider"
            }
          },
          "test_cards": {
            "$ref": "#/components/schemas/MerchantTestCards"
          }
        }
      },
      "MerchantListProvider": {
        "type": "object",
        "description": "One linked PSP of the registry row: the PA-59 execution snapshot only (the console renders the model/status badges, not the MID details).",
        "required": [
          "connector_code",
          "execution_model",
          "status"
        ],
        "properties": {
          "connector_code": {
            "type": "string",
            "description": "Connector code (`payadmit`, `apcopay`, …)."
          },
          "execution_model": {
            "type": "string",
            "enum": [
              "native_hyperswitch",
              "external_ucs"
            ],
            "description": "PA-59 execution model of the connector dispatch."
          },
          "status": {
            "type": "string",
            "enum": [
              "ENABLED",
              "DEPRECATED",
              "RETIRED"
            ],
            "description": "Connector lifecycle status (PA-59)."
          }
        }
      },
      "MerchantListStats": {
        "type": "object",
        "description": "Optional per-merchant turnover snapshot (`with_stats=1`): the 7d aggregate of `GET /v1/merchants/{id}/stats` (PA-65 semantics — GROSS EUR turnover of the approved family, minor units, previous-period delta, approval ratio).",
        "required": [
          "window",
          "window_days",
          "turnover_eur",
          "previous_turnover_eur",
          "transaction_count",
          "approved_count",
          "failed_count"
        ],
        "properties": {
          "window": {
            "type": "string",
            "enum": [
              "7d"
            ],
            "description": "Fixed snapshot window of the list."
          },
          "window_days": {
            "type": "integer",
            "enum": [
              7
            ]
          },
          "turnover_eur": {
            "type": "integer",
            "description": "Approved EUR volume, minor units (GROSS)."
          },
          "previous_turnover_eur": {
            "type": "integer",
            "description": "Same aggregate over the PREVIOUS period of the same length."
          },
          "transaction_count": {
            "type": "integer",
            "description": "All payments of the window (any state)."
          },
          "approved_count": {
            "type": "integer",
            "description": "Approved-family payments of the window."
          },
          "failed_count": {
            "type": "integer",
            "description": "FAILED payments of the window."
          },
          "approval_ratio": {
            "type": "number",
            "nullable": true,
            "description": "Approved / (approved + FAILED), percent two decimals; `null` when nothing is decided in the window."
          }
        }
      },
      "MerchantListEntry": {
        "type": "object",
        "description": "One merchant of the registry page.",
        "required": [
          "merchant_id",
          "name",
          "currencies",
          "providers",
          "route_targets_count",
          "route_targets_statuses",
          "psp_connections_count",
          "webhook_configured",
          "created_at"
        ],
        "properties": {
          "merchant_id": {
            "type": "string",
            "description": "Prefixed merchant id (`mer_…`)."
          },
          "name": {
            "type": "string"
          },
          "country": {
            "type": "string",
            "nullable": true,
            "description": "Onboarding jurisdiction (ISO code), when set."
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Processing currency scope of the onboarding profile."
          },
          "providers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MerchantListProvider"
            }
          },
          "route_targets_count": {
            "type": "integer",
            "description": "Total route targets (any lifecycle state)."
          },
          "route_targets_statuses": {
            "type": "object",
            "additionalProperties": {
              "type": "integer"
            },
            "description": "Route-target lifecycle status counts (PA-58 states, sorted by status)."
          },
          "psp_connections_count": {
            "type": "integer",
            "description": "PA-136 live-fix (W6): LIVE (non-archived) `merchant_psp_connections` of the merchant — the «N PSP» counter of the registry row. Archived connections (`archived_at IS NOT NULL`) are historical and never route, so they are NOT counted. One grouped read per page."
          },
          "webhook_configured": {
            "type": "boolean",
            "description": "PA-13 registration invariant: URL+secret pair registered (the secret itself is never projected)."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "stats": {
            "$ref": "#/components/schemas/MerchantListStats"
          }
        }
      },
      "MerchantListResponse": {
        "type": "object",
        "description": "The server-side merchant registry of the tenant (PA-69) — replaces the PA-52 localStorage registry.",
        "required": [
          "tenant_id",
          "total",
          "limit",
          "offset",
          "count",
          "with_stats",
          "merchants"
        ],
        "properties": {
          "tenant_id": {
            "type": "string",
            "description": "The authenticated tenant (the Bearer principal) — the console uses it to prefill the PA-24 tenant-key rotation form."
          },
          "total": {
            "type": "integer",
            "description": "Total merchants matching the filter (independent of the page)."
          },
          "limit": {
            "type": "integer"
          },
          "offset": {
            "type": "integer"
          },
          "count": {
            "type": "integer",
            "description": "Merchants on this page."
          },
          "q": {
            "type": "string",
            "nullable": true,
            "description": "Echoed search filter (`null` = no filter)."
          },
          "with_stats": {
            "type": "boolean",
            "description": "Echoed `with_stats` flag."
          },
          "merchants": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MerchantListEntry"
            }
          }
        }
      },
      "PayoutListItem": {
        "type": "object",
        "description": "One payout of the list page: the queue/grid columns (gate details — decisions and attempts — stay on the per-payout read).",
        "required": [
          "payout_id",
          "merchant_id",
          "status",
          "amount",
          "currency",
          "customer_reference",
          "version",
          "created_at"
        ],
        "properties": {
          "payout_id": {
            "type": "string",
            "description": "Prefixed payout id (`po_…`)."
          },
          "merchant_id": {
            "type": "string",
            "description": "Prefixed merchant id (`mer_…`)."
          },
          "status": {
            "type": "string",
            "enum": [
              "CREATED",
              "AWAITING_APPROVAL",
              "APPROVED",
              "PROCESSING",
              "COMPLETED",
              "DECLINED",
              "FAILED_TECHNICAL",
              "CANCELLED",
              "UNKNOWN_PENDING_SYNC"
            ],
            "description": "ADR-0004 §4.2 payout lifecycle state."
          },
          "amount": {
            "type": "integer",
            "description": "Amount in minor units."
          },
          "currency": {
            "type": "string"
          },
          "customer_reference": {
            "type": "string",
            "description": "Casino-side player reference."
          },
          "version": {
            "type": "integer",
            "description": "Optimistic-concurrency version of the aggregate."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "PayoutListResponse": {
        "type": "object",
        "description": "The tenant payout list page (PA-69) — the console approval queue base.",
        "required": [
          "total",
          "limit",
          "offset",
          "count",
          "payouts"
        ],
        "properties": {
          "total": {
            "type": "integer",
            "description": "Total payouts matching the filter (independent of the page)."
          },
          "limit": {
            "type": "integer"
          },
          "offset": {
            "type": "integer"
          },
          "count": {
            "type": "integer",
            "description": "Payouts on this page."
          },
          "status": {
            "type": "string",
            "enum": [
              "CREATED",
              "AWAITING_APPROVAL",
              "APPROVED",
              "PROCESSING",
              "COMPLETED",
              "DECLINED",
              "FAILED_TECHNICAL",
              "CANCELLED",
              "UNKNOWN_PENDING_SYNC"
            ],
            "nullable": true,
            "description": "Echoed status filter (`null` = no filter)."
          },
          "payouts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PayoutListItem"
            }
          }
        }
      },
      "DispatchJournalHealth": {
        "type": "object",
        "description": "PA-46 dispatch-journal health block of the reconciliation snapshot.",
        "required": [
          "unresolved_count"
        ],
        "properties": {
          "unresolved_count": {
            "type": "integer",
            "description": "Unresolved (potentially in-flight) dispatches of the tenant; 0 = nothing for the sync-worker recovery to do."
          },
          "oldest_unresolved_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "Oldest unresolved dispatch (`null` = none)."
          },
          "oldest_unresolved_age_secs": {
            "type": "integer",
            "nullable": true,
            "description": "Age of the oldest unresolved dispatch in seconds — compare against `sync_recovery_stale_secs`."
          }
        }
      },
      "ReconciliationHealthResponse": {
        "type": "object",
        "description": "The tenant-wide current-state reconciliation snapshot (PA-69) — no window: monitoring asks what is stuck NOW.",
        "required": [
          "tenant_id",
          "dispatch_journal",
          "stuck_checkouts",
          "unknown_pending_sync",
          "webhook_pending",
          "webhook_dead",
          "stale_checkout_threshold_mins",
          "sync_recovery_stale_secs",
          "generated_at"
        ],
        "properties": {
          "tenant_id": {
            "type": "string"
          },
          "dispatch_journal": {
            "$ref": "#/components/schemas/DispatchJournalHealth"
          },
          "stuck_checkouts": {
            "type": "integer",
            "description": "PENDING payments with a PENDING latest attempt older than `stale_checkout_threshold_mins` (the PA-36 reconcile candidates)."
          },
          "unknown_pending_sync": {
            "type": "integer",
            "description": "Payments in `UNKNOWN_PENDING_SYNC`."
          },
          "webhook_pending": {
            "type": "integer",
            "description": "Outbox rows currently awaiting delivery."
          },
          "webhook_dead": {
            "type": "integer",
            "description": "Dead-lettered outbox rows (the page view: `GET /v1/ops/outbox/dead`)."
          },
          "stale_checkout_threshold_mins": {
            "type": "integer",
            "description": "The reconcile threshold in effect (`PA_RECONCILE_AFTER_MINS`)."
          },
          "sync_recovery_stale_secs": {
            "type": "integer",
            "description": "The recovery staleness guard in effect (`PA_SYNC_RECOVERY_STALE_SECS`)."
          },
          "generated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "OutboxDeadLetter": {
        "type": "object",
        "description": "One dead-lettered delivery of the tenant (attempts/last-error facts — the stored payload is never projected).",
        "required": [
          "event_id",
          "event_type",
          "payment_id",
          "merchant_id",
          "attempts",
          "created_at"
        ],
        "properties": {
          "event_id": {
            "type": "string",
            "description": "PA event id (`PA-Event-Id` of the delivery)."
          },
          "event_type": {
            "type": "string",
            "description": "PA event type (`payment.authorized`, …)."
          },
          "payment_id": {
            "type": "string"
          },
          "merchant_id": {
            "type": "string"
          },
          "attempts": {
            "type": "integer",
            "description": "Delivery attempts made."
          },
          "last_error": {
            "type": "string",
            "nullable": true,
            "description": "Last error class of the delivery."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "OutboxDeadResponse": {
        "type": "object",
        "description": "The bounded newest-first dead-letter page plus the honest total backlog count (PA-69).",
        "required": [
          "tenant_id",
          "dead_count",
          "limit",
          "count",
          "letters",
          "generated_at"
        ],
        "properties": {
          "tenant_id": {
            "type": "string"
          },
          "dead_count": {
            "type": "integer",
            "description": "ALL dead letters of the tenant (independent of the page)."
          },
          "limit": {
            "type": "integer"
          },
          "count": {
            "type": "integer",
            "description": "Letters on this page."
          },
          "letters": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/OutboxDeadLetter"
            }
          },
          "generated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "RateLimitBucketUsage": {
        "type": "object",
        "description": "Live usage of one endpoint bucket of the calling tenant (memory backend).",
        "required": [
          "endpoint",
          "used",
          "limit"
        ],
        "properties": {
          "endpoint": {
            "type": "string",
            "description": "Route-pattern bucket key (instance paths collapse onto it)."
          },
          "used": {
            "type": "integer",
            "description": "Requests inside the current window."
          },
          "limit": {
            "type": "integer",
            "description": "Effective limit (override or default)."
          }
        }
      },
      "RateLimitSnapshotResponse": {
        "type": "object",
        "description": "The PA-47 read-only rate-limit snapshot (PA-69). `tenant_buckets`/`tracked` are the live memory-backend state; on the Redis backend they are absent (the shared buckets live in Redis — honest MVP gap).",
        "required": [
          "backend",
          "window_secs",
          "default_rpm",
          "overrides",
          "unauth_ip_rpm",
          "generated_at"
        ],
        "properties": {
          "backend": {
            "type": "string",
            "enum": [
              "memory",
              "redis"
            ],
            "description": "PA-47 backend selection."
          },
          "window_secs": {
            "type": "integer",
            "description": "Sliding-window length (seconds)."
          },
          "default_rpm": {
            "type": "integer",
            "description": "Default per-tenant per-endpoint limit (requests per window)."
          },
          "overrides": {
            "type": "object",
            "additionalProperties": {
              "type": "integer"
            },
            "description": "Per-endpoint overrides (sorted by endpoint)."
          },
          "unauth_ip_rpm": {
            "type": "integer",
            "description": "Unauthenticated per-IP window limit (PA-47)."
          },
          "tenant_buckets": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/RateLimitBucketUsage"
            },
            "nullable": true,
            "description": "Live per-endpoint usage of the CALLING tenant (absent on the Redis backend)."
          },
          "tracked": {
            "type": "object",
            "nullable": true,
            "description": "Process-wide tracked-bucket counters `{tenant_buckets, ip_buckets}` (absent on the Redis backend)."
          },
          "generated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "PspCapabilities": {
        "type": "object",
        "description": "PA-53 capability anкета flags (MVP, booleans). Non-secret provider-level product claims the PSP confirms through the portal.",
        "required": [
          "s2s_card",
          "redirect_hpp",
          "three_ds",
          "refund",
          "idempotency",
          "lookup"
        ],
        "properties": {
          "s2s_card": {
            "type": "boolean",
            "description": "S2S raw-card processing (DirectConnect)."
          },
          "redirect_hpp": {
            "type": "boolean",
            "description": "Hosted/redirect HPP processing."
          },
          "three_ds": {
            "type": "boolean",
            "description": "3DS (frictionless/challenge) support."
          },
          "refund": {
            "type": "boolean",
            "description": "Refund (incl. partial) support."
          },
          "idempotency": {
            "type": "boolean",
            "description": "Native idempotency key semantics (safe retries)."
          },
          "lookup": {
            "type": "boolean",
            "description": "Lookup by PSP reference (recovery)."
          }
        }
      },
      "PspCapabilitiesSource": {
        "type": "string",
        "enum": [
          "default_snapshot",
          "psp_confirmed"
        ],
        "description": "`default_snapshot` = the static PA-53 research snapshot; `psp_confirmed` = the PSP's own anкета confirmation (evidence CONFIRMED_BY_PSP)."
      },
      "PspCapabilitiesView": {
        "type": "object",
        "description": "The effective capability snapshot: the confirmed flags (or the static default), their source and the confirmation time.",
        "allOf": [
          {
            "$ref": "#/components/schemas/PspCapabilities"
          },
          {
            "type": "object",
            "properties": {
              "source": {
                "$ref": "#/components/schemas/PspCapabilitiesSource"
              },
              "confirmed_at": {
                "type": "string",
                "format": "date-time",
                "nullable": true,
                "description": "RFC 3339 UTC time of the last confirmation (absent for the default snapshot)."
              }
            }
          }
        ]
      },
      "PspCapabilitiesPutRequest": {
        "type": "object",
        "required": [
          "capabilities"
        ],
        "properties": {
          "capabilities": {
            "$ref": "#/components/schemas/PspCapabilities"
          }
        }
      },
      "PspTestCard": {
        "type": "object",
        "description": "One sandbox test card of the PSP's terminal (public PSP fixture — not a credential).",
        "required": [
          "label",
          "number",
          "expiry",
          "note"
        ],
        "properties": {
          "label": {
            "type": "string"
          },
          "number": {
            "type": "string"
          },
          "expiry": {
            "type": "string"
          },
          "holder": {
            "type": "string",
            "nullable": true
          },
          "cvc": {
            "type": "string",
            "nullable": true
          },
          "note": {
            "type": "string",
            "description": "What the fixture proves."
          }
        }
      },
      "PspProfileResponse": {
        "type": "object",
        "required": [
          "connector_code",
          "display_name",
          "execution_model",
          "connector_status",
          "capabilities",
          "base_urls",
          "test_cards"
        ],
        "properties": {
          "connector_code": {
            "type": "string",
            "description": "The connector scope of the key (resolved FROM the key, not an input)."
          },
          "display_name": {
            "type": "string",
            "description": "The display name of the connector rows (fallback: the connector code)."
          },
          "execution_model": {
            "type": "string",
            "enum": [
              "native_hyperswitch",
              "external_ucs"
            ],
            "description": "PA-59 execution snapshot."
          },
          "connector_status": {
            "type": "string",
            "enum": [
              "ENABLED",
              "DEPRECATED",
              "RETIRED"
            ],
            "description": "PA-59 connector lifecycle status."
          },
          "connector_version": {
            "type": "string",
            "nullable": true,
            "description": "PA-59 connector version (fork MR commit); null = not recorded."
          },
          "capabilities": {
            "$ref": "#/components/schemas/PspCapabilitiesView"
          },
          "base_urls": {
            "$ref": "#/components/schemas/MerchantBaseUrls"
          },
          "test_cards": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PspTestCard"
            }
          }
        }
      },
      "PspRouteTargetBrief": {
        "type": "object",
        "required": [
          "rt_id",
          "status"
        ],
        "properties": {
          "rt_id": {
            "type": "string",
            "description": "PA Route Target id (`rt_…`)."
          },
          "status": {
            "type": "string",
            "enum": [
              "ENABLED",
              "DRAINING",
              "DEGRADED",
              "DISABLED"
            ],
            "description": "PA-58 lifecycle state of the Route Target (no priorities/weights — operator data)."
          }
        }
      },
      "PspMca": {
        "type": "object",
        "required": [
          "mca_id",
          "merchant_id",
          "merchant_name",
          "mid_label",
          "currencies",
          "countries",
          "execution_model",
          "connector_status",
          "route_targets"
        ],
        "properties": {
          "mca_id": {
            "type": "string",
            "description": "The fork MCA reference (`provider_accounts.external_mca_ref`) — the proxy address of the rotation, not a secret."
          },
          "merchant_id": {
            "type": "string"
          },
          "merchant_name": {
            "type": "string"
          },
          "mid_label": {
            "type": "string"
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "countries": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "execution_model": {
            "type": "string",
            "enum": [
              "native_hyperswitch",
              "external_ucs"
            ]
          },
          "connector_status": {
            "type": "string",
            "enum": [
              "ENABLED",
              "DEPRECATED",
              "RETIRED"
            ]
          },
          "connector_version": {
            "type": "string",
            "nullable": true
          },
          "route_targets": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PspRouteTargetBrief"
            }
          }
        }
      },
      "PspMcaListResponse": {
        "type": "object",
        "required": [
          "connector_code",
          "count",
          "mcas"
        ],
        "properties": {
          "connector_code": {
            "type": "string"
          },
          "count": {
            "type": "integer"
          },
          "mcas": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PspMca"
            }
          }
        }
      },
      "PspDispatchSummary": {
        "type": "object",
        "required": [
          "payment_id",
          "state",
          "attempt_status",
          "amount",
          "currency",
          "merchant_id",
          "mid_label",
          "created_at"
        ],
        "properties": {
          "payment_id": {
            "type": "string"
          },
          "psp_reference": {
            "type": "string",
            "nullable": true,
            "description": "The PSP's own transaction reference (attempts.provider_transaction_id — the pspid of the Apcopay model)."
          },
          "state": {
            "type": "string",
            "enum": [
              "PENDING",
              "AUTHORIZED",
              "CAPTURED",
              "PARTIALLY_REFUNDED",
              "REFUNDED",
              "FAILED",
              "UNKNOWN_PENDING_SYNC"
            ],
            "description": "PA payment state."
          },
          "attempt_status": {
            "type": "string",
            "enum": [
              "PENDING",
              "AUTHORIZED",
              "DECLINED_SOFT",
              "DECLINED_HARD",
              "UNKNOWN",
              "FAILED_TECHNICAL"
            ],
            "description": "The PSP's own attempt status."
          },
          "provider_code": {
            "type": "string",
            "nullable": true,
            "description": "Verbatim provider (bank) code."
          },
          "provider_status": {
            "type": "string",
            "nullable": true,
            "description": "Verbatim provider status echo."
          },
          "amount": {
            "type": "integer",
            "description": "Minor units (cents)."
          },
          "currency": {
            "type": "string"
          },
          "merchant_id": {
            "type": "string"
          },
          "mid_label": {
            "type": "string"
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "description": "Attempt start (dispatch time), RFC 3339 UTC."
          },
          "finished_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          }
        }
      },
      "PspDispatchListResponse": {
        "type": "object",
        "required": [
          "connector_code",
          "total",
          "limit",
          "offset",
          "count",
          "payments"
        ],
        "properties": {
          "connector_code": {
            "type": "string"
          },
          "total": {
            "type": "integer"
          },
          "limit": {
            "type": "integer"
          },
          "offset": {
            "type": "integer"
          },
          "count": {
            "type": "integer"
          },
          "payments": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PspDispatchSummary"
            }
          }
        }
      },
      "PspDispatchStats": {
        "type": "object",
        "required": [
          "pending",
          "authorized",
          "declined_soft",
          "declined_hard",
          "unknown",
          "failed_technical"
        ],
        "properties": {
          "pending": {
            "type": "integer"
          },
          "authorized": {
            "type": "integer"
          },
          "declined_soft": {
            "type": "integer"
          },
          "declined_hard": {
            "type": "integer"
          },
          "unknown": {
            "type": "integer"
          },
          "failed_technical": {
            "type": "integer"
          },
          "success_rate": {
            "type": "number",
            "nullable": true,
            "description": "authorized / (authorized + declined_soft + declined_hard), percent with two decimals; null = nothing decided in the window (never 0%)."
          }
        }
      },
      "PspDeclineCodeCount": {
        "type": "object",
        "required": [
          "provider_code",
          "count"
        ],
        "properties": {
          "provider_code": {
            "type": "string",
            "description": "Verbatim bank code (empty = no code recorded)."
          },
          "count": {
            "type": "integer"
          }
        }
      },
      "PspDailyRollup": {
        "type": "object",
        "required": [
          "date",
          "currency",
          "count",
          "amount_minor"
        ],
        "properties": {
          "date": {
            "type": "string",
            "description": "UTC day (YYYY-MM-DD)."
          },
          "currency": {
            "type": "string"
          },
          "count": {
            "type": "integer",
            "description": "Dispatch count that day."
          },
          "amount_minor": {
            "type": "integer",
            "description": "Sum of payment amounts, minor units (never mixed across currencies)."
          }
        }
      },
      "PspHealthResponse": {
        "type": "object",
        "required": [
          "connector_code",
          "window",
          "window_days",
          "dispatch_stats",
          "journal_unresolved",
          "declines_breakdown",
          "daily",
          "generated_at"
        ],
        "properties": {
          "connector_code": {
            "type": "string"
          },
          "window": {
            "type": "string",
            "enum": [
              "7d",
              "30d"
            ]
          },
          "window_days": {
            "type": "integer"
          },
          "dispatch_stats": {
            "$ref": "#/components/schemas/PspDispatchStats"
          },
          "journal_unresolved": {
            "type": "integer",
            "description": "Unresolved PA-46 dispatch-journal rows (in-flight or crashed dispatches)."
          },
          "declines_breakdown": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PspDeclineCodeCount"
            }
          },
          "daily": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PspDailyRollup"
            }
          },
          "generated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "PspCredentialsRequest": {
        "type": "object",
        "description": "The NEW credential values of the MCA (the COMPLETE SignatureKey set — the fork replaces the whole credential object; partial sets are rejected with 422). NEVER persisted in PA: streamed to the fork admin API, dropped after the call, never logged; the audit event carries the field NAMES only.",
        "properties": {
          "api_key": {
            "type": "string",
            "maxLength": 4096,
            "description": "API key of the PSP terminal (SignatureKey.api_key). Absent/empty → 422 (the rotation replaces the FULL credential set on the fork)."
          },
          "key1": {
            "type": "string",
            "maxLength": 4096,
            "description": "Terminal/brand key (SignatureKey.key1). Absent/empty → 422 (the rotation replaces the FULL credential set on the fork)."
          },
          "api_secret": {
            "type": "string",
            "maxLength": 4096,
            "description": "API secret (SignatureKey.api_secret). Absent/empty → 422 (the rotation replaces the FULL credential set on the fork)."
          }
        }
      },
      "PspCredentialsRotatedResponse": {
        "type": "object",
        "required": [
          "connector_code",
          "mca_id",
          "merchant_id",
          "mid_label",
          "rotated_fields",
          "rotated_at"
        ],
        "properties": {
          "connector_code": {
            "type": "string"
          },
          "mca_id": {
            "type": "string"
          },
          "merchant_id": {
            "type": "string"
          },
          "mid_label": {
            "type": "string"
          },
          "rotated_fields": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "The rotated FIELD NAMES only — the values are never echoed."
          },
          "rotated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "SdkCaptureRequest": {
        "type": "object",
        "required": [
          "card_number",
          "cvc",
          "expiry_month",
          "expiry_year"
        ],
        "properties": {
          "card_number": {
            "type": "string",
            "description": "PAN, digits only (12-19, no separators, Luhn-checked server-side). PCI: exists only in flight — never logged, persisted or echoed."
          },
          "cvc": {
            "type": "string",
            "description": "CVC, 3-4 digits. PCI: exists only in flight."
          },
          "expiry_month": {
            "type": "string",
            "description": "Expiry month, `01`-`12`."
          },
          "expiry_year": {
            "type": "string",
            "description": "Expiry year, 4 digits (`2030`)."
          },
          "card_holder_name": {
            "type": "string",
            "nullable": true,
            "description": "Optional cardholder name (max 128 chars), forwarded to the capture surface."
          },
          "publishable_key": {
            "type": "string",
            "nullable": true,
            "description": "Optional fallback transport of the publishable key (header `X-Publishable-Key` is canonical)."
          }
        }
      },
      "SdkCaptureResponse": {
        "type": "object",
        "required": [
          "vault_token",
          "brand",
          "last4"
        ],
        "properties": {
          "vault_token": {
            "type": "string",
            "description": "Single-use vault token of the freshly tokenized card (fork `pm_...`). The casino frontend forwards it to its backend, which registers the instrument via `POST /v1/payment-instruments`. Consumed exactly once."
          },
          "brand": {
            "type": "string",
            "description": "Masked card brand from the capture surface (`UNKNOWN` fallback)."
          },
          "last4": {
            "type": "string",
            "description": "Last four digits of the PAN (masked metadata)."
          },
          "exp_month": {
            "type": "string",
            "nullable": true
          },
          "exp_year": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "IssueMerchantKeyResponse": {
        "type": "object",
        "required": [
          "merchant_id",
          "api_key",
          "created_at"
        ],
        "properties": {
          "merchant_id": {
            "type": "string",
            "description": "Merchant id (`mer_…`) the key is scoped to."
          },
          "api_key": {
            "type": "string",
            "description": "The raw merchant-scoped API key (`mer_sk_…`) — shown EXACTLY ONCE, never surfaced again, never logged; only its SHA-256 hash is persisted (PA-72)."
          },
          "created_at": {
            "type": "string",
            "description": "RFC 3339 issue/rotate time of the key."
          }
        }
      },
      "MerchantCreatePayoutRequest": {
        "type": "object",
        "description": "Request body of `POST /v1/merchants/{id}/payouts` — the merchant-scoped payout create. Unlike the operator `CreatePayoutRequest` there is NO `merchant_id` in the body: the payout is created FOR the path merchant (a merchant-scoped key may only address its own merchant — a foreign path is a plain `404`). The receiver is EITHER `instrument_id` (the player's payment instrument of THIS merchant — otherwise `422 unknown_instrument`) OR `receiver_card` (PA-93, the H2H raw-card receiver: the PCI DSS certified merchant's backend sends the player's card inline, NO CVV — a credit needs none; requires the H2H gate — `422 h2h_not_enabled` — and an explicit `customer_reference`). The forms are mutually exclusive (both → `422 invalid_request`, neither → `422 invalid_request`). The raw-card values are transit only: PA persists the MASKED snapshot (brand + last4 + expiry) — PAN/holder never enter the payout record, audit trail or webhooks. Unknown top-level fields are rejected.",
        "required": [
          "amount",
          "currency"
        ],
        "properties": {
          "instrument_id": {
            "type": "string",
            "description": "Card-based receiver form: PA instrument of the path merchant (`pin_…`, PA-13). Must reference a payment instrument OF THIS MERCHANT in this tenant — an unknown or a sibling merchant's instrument is `422 unknown_instrument`. Payout instrument policy (PA-87, payout-to-deposit-card): the receiver accepts status `ACTIVE` or `USED` — an instrument a deposit already consumed (`USED`) stays a valid payout receiver, and the payout does NOT consume the instrument (repeated payouts to the same `pin_…` are valid; the operator approval gate and the payout limits own the risk). A `DEACTIVATED` instrument is `422 instrument_not_payout_eligible`. Mutually exclusive with `receiver_card`."
          },
          "amount": {
            "type": "integer",
            "minimum": 1,
            "description": "Amount in minor units."
          },
          "currency": {
            "type": "string",
            "description": "ISO 4217 alpha-3 currency."
          },
          "customer_reference": {
            "type": "string",
            "description": "Casino-side player reference. Optional on the instrument form — defaults to the instrument's ownership context when the instrument carries one (required explicitly otherwise); REQUIRED on the `receiver_card` form (no instrument ownership context to default from). Validated by the shared validator: ≤ 255 characters, restricted charset, Luhn PAN probe."
          },
          "receiver": {
            "type": "object",
            "description": "Masked receiver metadata; PAN/CVV keys are rejected with `422 invalid_request` (`receiver must not contain card data fields (PAN/CVV)`)."
          },
          "risk_context": {
            "type": "object",
            "description": "Risk context consumed by the payout approval policy; PAN/CVV keys are rejected."
          },
          "retry_of_payout_id": {
            "type": "string",
            "description": "Original payout when retrying after a confirmed DECLINED (a new payout, not a second financial attempt)."
          },
          "receiver_card": {
            "type": "object",
            "required": [
              "card_number",
              "card_exp_month",
              "card_exp_year",
              "card_holder_name"
            ],
            "description": "PA-93: the H2H raw-card receiver — the payout CREDITS this card. Gated by the H2H flags (deployment kill-switch + per-merchant `merchants.h2h_enabled`, any off level → `422 h2h_not_enabled`, checked BEFORE validation) and validated fail-fast (Luhn/expiry/holder). NO CVV field by contract: a credit needs none (the PSP add_card/WITHDRAWAL flow accepts the card without CVV); a sent `card_cvc` is rejected loudly (unknown field). Transit discipline: the payout record receives the MASKED snapshot (brand + last4 + expiry) — PAN/holder never enter storage; raw-card payouts draw from the SAME per-merchant H2H rate-limit bucket as raw-card deposits (`429 rate_limited` + `Retry-After` on excess). The PSP dispatch itself stays Phase 2 (PA-32): the payout lands in `AWAITING_APPROVAL` with the masked snapshot.",
            "properties": {
              "card_number": {
                "type": "string",
                "description": "Digits-only PAN, 12–19 digits with a valid Luhn checksum. Otherwise `422 invalid_card_number` (the problem message names the constraint, never the value)."
              },
              "card_exp_month": {
                "type": [
                  "integer",
                  "string"
                ],
                "description": "Expiry month, 1–12 (number or numeric string). Otherwise `422 invalid_card_expiry`."
              },
              "card_exp_year": {
                "type": [
                  "integer",
                  "string"
                ],
                "description": "4-digit expiry year (2000–2199); the card is valid through the end of its expiry month. Otherwise `422 invalid_card_expiry`; an already-over window → `422 card_expired`."
              },
              "card_holder_name": {
                "type": "string",
                "description": "Cardholder name, 1–255 characters after trim. Otherwise `422 invalid_card_holder`."
              }
            }
          }
        }
      },
      "MerchantPayoutListItem": {
        "type": "object",
        "description": "One payout of the merchant's own list page (PA-83) — the grid columns of the portal Payouts tab, with the masked instrument label of the receiver card.",
        "required": [
          "payout_id",
          "status",
          "amount",
          "currency",
          "customer_reference",
          "version",
          "created_at"
        ],
        "properties": {
          "payout_id": {
            "type": "string",
            "description": "Prefixed payout id (`po_…`)."
          },
          "status": {
            "type": "string",
            "enum": [
              "CREATED",
              "AWAITING_APPROVAL",
              "APPROVED",
              "PROCESSING",
              "COMPLETED",
              "DECLINED",
              "FAILED_TECHNICAL",
              "CANCELLED",
              "UNKNOWN_PENDING_SYNC"
            ],
            "description": "ADR-0004 §4.2 payout lifecycle state."
          },
          "amount": {
            "type": "integer",
            "description": "Amount in minor units."
          },
          "currency": {
            "type": "string"
          },
          "customer_reference": {
            "type": "string",
            "description": "Casino-side player reference."
          },
          "instrument_id": {
            "type": "string",
            "description": "Receiver instrument reference as stored on the payout (`pin_…`). Present when the payout was created with an instrument."
          },
          "instrument": {
            "type": "string",
            "description": "Masked instrument label (`VISA •••• 4242`) — PA never projects a PAN segment. Present for BOTH receiver forms: the instrument JOIN (instrument payouts) and PA's own masked raw-card snapshot (PA-93 receiver payouts)."
          },
          "version": {
            "type": "integer",
            "description": "Optimistic-concurrency version of the aggregate."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "MerchantPayoutListResponse": {
        "type": "object",
        "description": "Response of `GET /v1/merchants/{id}/payouts` (PA-83) — the merchant's own payouts, newest first, filter-scoped total, clamped page.",
        "required": [
          "total",
          "limit",
          "offset",
          "count",
          "payouts"
        ],
        "properties": {
          "total": {
            "type": "integer",
            "description": "Total payouts matching the filter (independent of the page)."
          },
          "limit": {
            "type": "integer"
          },
          "offset": {
            "type": "integer"
          },
          "count": {
            "type": "integer",
            "description": "Payouts on this page."
          },
          "status": {
            "type": "string",
            "enum": [
              "CREATED",
              "AWAITING_APPROVAL",
              "APPROVED",
              "PROCESSING",
              "COMPLETED",
              "DECLINED",
              "FAILED_TECHNICAL",
              "CANCELLED",
              "UNKNOWN_PENDING_SYNC"
            ],
            "description": "Echoed status filter (absent = no filter)."
          },
          "payouts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MerchantPayoutListItem"
            }
          }
        }
      },
      "SetMerchantPayoutsEnabledRequest": {
        "type": "object",
        "description": "Request body of `PUT /v1/merchants/{id}/payouts-enabled` (PA-83) — the operator toggle of the per-merchant payouts gate (admin-only).",
        "required": [
          "enabled"
        ],
        "properties": {
          "enabled": {
            "type": "boolean",
            "description": "Target gate state (`true` = the casino may create payouts for its own players through `POST /v1/merchants/{id}/payouts` — every payout still passes the operator approval gate)."
          },
          "reason": {
            "type": "string",
            "description": "Free-text operator reason, recorded in the `payout.payouts_enabled` audit event verbatim."
          }
        }
      },
      "SetMerchantPayoutsEnabledResponse": {
        "type": "object",
        "description": "The settled gate state of `PUT /v1/merchants/{id}/payouts-enabled`.",
        "required": [
          "merchant_id",
          "payouts_enabled"
        ],
        "properties": {
          "merchant_id": {
            "type": "string",
            "example": "mer_01900000-0000-7000-8000-000000000001"
          },
          "payouts_enabled": {
            "type": "boolean"
          }
        }
      },
      "SetTenantPayoutsEnabledRequest": {
        "type": "object",
        "required": [
          "enabled"
        ],
        "properties": {
          "enabled": {
            "type": "boolean",
            "description": "The target gate state (`true` = the payout domain is enabled for the tenant — the operator approval queue becomes reachable and the per-merchant gates may open the casino surfaces)."
          },
          "reason": {
            "type": "string",
            "description": "Free-text operator reason (recorded in the audit event verbatim)."
          }
        },
        "additionalProperties": false
      },
      "SetTenantPayoutsEnabledResponse": {
        "type": "object",
        "required": [
          "tenant_id",
          "payouts_enabled"
        ],
        "properties": {
          "tenant_id": {
            "type": "string",
            "description": "The tenant the gate was settled for (`tn_…`)."
          },
          "payouts_enabled": {
            "type": "boolean",
            "description": "The settled tenant-level payouts domain gate."
          }
        },
        "additionalProperties": false
      },
      "MerchantProviderState": {
        "type": "object",
        "required": [
          "provider_code",
          "enabled"
        ],
        "properties": {
          "provider_code": {
            "type": "string",
            "description": "Connector code (lowercase identifier, e.g. `payadmit`)."
          },
          "enabled": {
            "type": "boolean",
            "description": "`false` = the merchant disabled this PSP (an explicit override row); `true` = enabled by default (no override row) or by an explicit re-enable."
          },
          "updated_at": {
            "type": "string",
            "format": "date-time",
            "description": "Update time of the explicit override row; absent when the state is the default-inherited one."
          },
          "sub_provider": {
            "type": "string",
            "description": "PA-105 granularity: the sub-provider the row scopes to (Apcopay `provider_routing.bank_code`, e.g. `BOVPAYON`). Absent = the MASTER toggle of the whole connector (the pre-granularity row shape)."
          },
          "operator_locked": {
            "type": "boolean",
            "description": "PA-116: present (`true`) ONLY in the admin-scope view of an operator-locked row — the operator disabled this PSP for the merchant and the merchant cannot re-enable it (the merchant scope never sees the row at all; its `PUT` answers `403 provider_locked_by_operator`). Only an admin `enabled=true` clears the lock. Absent = a plain PA-105 override row (merchant-visible, merchant-reversible)."
          }
        },
        "description": "One effective per-merchant PSP state. PA-105 granularity: a multiplexing PSP (Apcopay) is enumerated per sub-provider — one row per `sub_provider` (the `provider_routing.bank_code` of its Route Targets, PA-112) PLUS the master row (`sub_provider` absent) for targets without provider routing. The master row switches the WHOLE connector (every sub-provider included); a sub row switches only the targets that declare that bank_code. The EFFECTIVE state of a target with bank_code X: the master row not disabled AND the X row not disabled."
      },
      "MerchantProvidersResponse": {
        "type": "object",
        "required": [
          "providers"
        ],
        "properties": {
          "providers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MerchantProviderState"
            },
            "description": "One row per operator-configured PSP of the merchant, ordered by provider code."
          }
        }
      },
      "SetMerchantProviderRequest": {
        "type": "object",
        "required": [
          "enabled"
        ],
        "properties": {
          "enabled": {
            "type": "boolean",
            "description": "Target state: `false` removes the provider's route targets from this merchant's NEW-payment routing eligibility; `true` re-enables it."
          },
          "sub_provider": {
            "type": "string",
            "description": "PA-105 granularity: the sub-provider to toggle (Apcopay `provider_routing.bank_code`, e.g. `BOVPAYON`). Absent = the MASTER toggle of the whole connector (every sub-provider included). A sub-provider the operator has NOT configured for the merchant is a plain 404."
          },
          "operator_locked": {
            "type": "boolean",
            "description": "OPERATOR-ONLY field. With the admin key: `true` + `enabled=false` is the operator-enforced disable (the PSP disappears from the merchant cabinet and the merchant cannot re-enable it — PA-116); absent or `false` with `enabled=false` is the SOFT disable — the merchant keeps seeing the row as disabled and may re-enable it itself. `enabled=true` always clears the lock. A merchant-scoped request carrying the field AT ALL answers `422 operator_locked_is_operator_only`."
          }
        },
        "description": "Request body of the toggle. PA-105 granularity: `sub_provider` scopes the toggle to ONE sub-provider of the connector; the absent field keeps the master semantics (the whole connector, all sub-providers included)."
      },
      "SetMerchantProviderResponse": {
        "type": "object",
        "required": [
          "provider_code",
          "enabled",
          "last_enabled"
        ],
        "properties": {
          "provider_code": {
            "type": "string"
          },
          "enabled": {
            "type": "boolean",
            "description": "The settled state of the PSP for this merchant."
          },
          "last_enabled": {
            "type": "boolean",
            "description": "`true` = this toggle disabled the LAST enabled PSP of the merchant: acceptance of payments answers 422 no_eligible_route until another PSP is re-enabled."
          },
          "sub_provider": {
            "type": "string",
            "description": "PA-105 granularity: the toggled sub-provider (`null`/absent = the master toggle of the whole connector)."
          },
          "operator_locked": {
            "type": "boolean",
            "description": "`true` = the operator-enforced disable (the row is hidden from the merchant and cannot be re-enabled by the merchant). Absent = an unlocked row (soft-disabled rows included — the merchant may re-enable them)."
          }
        },
        "description": "The settled state of the toggled (provider, sub-provider) key."
      },
      "SetMerchantPayoutSelfApprovalRequest": {
        "type": "object",
        "description": "Request body of `PUT /v1/merchants/{id}/payout-self-approval` (PA-107) — the operator toggle of the merchant payout SELF-approval flag (admin-only; a merchant-scoped key answers `403 forbidden` — the merchant may not grant itself the four-eyes waiver). Fail-closed: the default `false` keeps the operator approval gate in front of every payout of this merchant.",
        "required": [
          "enabled"
        ],
        "properties": {
          "enabled": {
            "type": "boolean",
            "description": "Target flag state (`true` = the merchant may approve/decline its own `AWAITING_APPROVAL` payouts through `POST /v1/merchants/{id}/payouts/{payout_id}/approve|decline` and the `/portal` Payouts tab)."
          },
          "reason": {
            "type": "string",
            "description": "Free-text operator reason, recorded in the `merchant.payout_self_approval` audit event verbatim."
          }
        }
      },
      "SetMerchantPayoutSelfApprovalResponse": {
        "type": "object",
        "description": "The settled flag state of `PUT /v1/merchants/{id}/payout-self-approval` (PA-107).",
        "required": [
          "merchant_id",
          "payout_self_approval"
        ],
        "properties": {
          "merchant_id": {
            "type": "string",
            "example": "mer_01900000-0000-7000-8000-000000000001"
          },
          "payout_self_approval": {
            "type": "boolean"
          }
        }
      },
      "PaymentMethodDefinition": {
        "type": "object",
        "required": [
          "id",
          "code",
          "name",
          "category",
          "supported_operations",
          "status"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "code": {
            "type": "string",
            "example": "card"
          },
          "name": {
            "type": "string"
          },
          "category": {
            "type": "string",
            "enum": [
              "CARD",
              "APPLE_PAY",
              "GOOGLE_PAY",
              "OPEN_BANKING",
              "BANK_TRANSFER"
            ]
          },
          "supported_operations": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "deposit",
                "payout",
                "refund"
              ]
            }
          },
          "description": {
            "type": "string"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "status": {
            "type": "string",
            "enum": [
              "ACTIVE",
              "DEPRECATED",
              "HIDDEN"
            ],
            "description": "PA-136 lifecycle: ACTIVE = offered, DEPRECATED = routable but not offered for new configuration, HIDDEN = not offered."
          }
        }
      },
      "PaymentMethodListResponse": {
        "type": "object",
        "required": [
          "methods"
        ],
        "properties": {
          "methods": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PaymentMethodDefinition"
            }
          }
        }
      },
      "WebhookProfile": {
        "type": "object",
        "required": [
          "id",
          "psp_id",
          "verifier_type",
          "supported_events"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "psp_id": {
            "type": "string",
            "format": "uuid"
          },
          "verifier_type": {
            "type": "string",
            "enum": [
              "hmac",
              "shared_token",
              "rsa",
              "basic",
              "none",
              "custom"
            ]
          },
          "signature_header": {
            "type": "string"
          },
          "timestamp_header": {
            "type": "string"
          },
          "replay_tolerance": {
            "type": "integer"
          },
          "dedup_key": {
            "type": "string"
          },
          "supported_events": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "callback_endpoint_pattern": {
            "type": "string"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "WebhookProfileListResponse": {
        "type": "object",
        "required": [
          "profiles"
        ],
        "properties": {
          "profiles": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/WebhookProfile"
            }
          }
        }
      },
      "CreateWebhookProfileRequest": {
        "type": "object",
        "required": [
          "verifier_type"
        ],
        "properties": {
          "verifier_type": {
            "type": "string",
            "enum": [
              "hmac",
              "shared_token",
              "rsa",
              "basic",
              "none",
              "custom"
            ]
          },
          "signature_header": {
            "type": "string"
          },
          "timestamp_header": {
            "type": "string"
          },
          "replay_tolerance": {
            "type": "integer"
          },
          "dedup_key": {
            "type": "string"
          },
          "supported_events": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "callback_endpoint_pattern": {
            "type": "string"
          }
        }
      },
      "UpdateWebhookProfileRequest": {
        "type": "object",
        "required": [
          "verifier_type"
        ],
        "properties": {
          "verifier_type": {
            "type": "string",
            "enum": [
              "hmac",
              "shared_token",
              "rsa",
              "basic",
              "none",
              "custom"
            ]
          },
          "signature_header": {
            "type": "string"
          },
          "timestamp_header": {
            "type": "string"
          },
          "replay_tolerance": {
            "type": "integer"
          },
          "dedup_key": {
            "type": "string"
          },
          "supported_events": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "callback_endpoint_pattern": {
            "type": "string"
          }
        }
      },
      "PspMethod": {
        "type": "object",
        "required": [
          "id",
          "psp_id",
          "method_id",
          "method_code",
          "method_name",
          "method_category",
          "transaction_type",
          "currencies",
          "countries",
          "availability"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "psp_id": {
            "type": "string",
            "format": "uuid"
          },
          "method_id": {
            "type": "string",
            "format": "uuid"
          },
          "method_code": {
            "type": "string",
            "example": "card"
          },
          "method_name": {
            "type": "string"
          },
          "method_category": {
            "type": "string",
            "enum": [
              "CARD",
              "APPLE_PAY",
              "GOOGLE_PAY",
              "OPEN_BANKING",
              "BANK_TRANSFER"
            ]
          },
          "transaction_type": {
            "type": "string",
            "enum": [
              "deposit",
              "payout"
            ]
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "countries": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "min_amount": {
            "type": "integer",
            "format": "int64"
          },
          "max_amount": {
            "type": "integer",
            "format": "int64"
          },
          "availability": {
            "type": "string",
            "enum": [
              "enabled",
              "available",
              "blocked",
              "hidden"
            ]
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "PspMethodListResponse": {
        "type": "object",
        "required": [
          "methods"
        ],
        "properties": {
          "methods": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PspMethod"
            }
          }
        }
      },
      "UpsertPspMethodRequest": {
        "type": "object",
        "required": [
          "method_id",
          "availability"
        ],
        "properties": {
          "method_id": {
            "type": "string",
            "format": "uuid"
          },
          "transaction_type": {
            "type": "string",
            "enum": [
              "deposit",
              "payout"
            ],
            "default": "deposit"
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "default": []
          },
          "countries": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "default": []
          },
          "min_amount": {
            "type": "integer",
            "format": "int64"
          },
          "max_amount": {
            "type": "integer",
            "format": "int64"
          },
          "availability": {
            "type": "string",
            "enum": [
              "enabled",
              "available",
              "blocked",
              "hidden"
            ]
          }
        }
      },
      "AddRouteRequest": {
        "type": "object",
        "required": [
          "method_id"
        ],
        "properties": {
          "method_id": {
            "type": "string",
            "format": "uuid"
          },
          "merchant_terminal_id": {
            "type": "integer",
            "format": "int64",
            "nullable": true,
            "description": "NULL = account-level route (terminal_policy=NONE). Such a route carries its executing Route Target in `route_target_id` (PA-137); mutually exclusive with it (`422 invalid_request` when both are set)."
          },
          "route_target_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "PA-137: the EXECUTING Route Target of an ACCOUNT-level route (migration 0045). The route then needs no terminal: the execution resolves the connection through the Route Target's connector (`providers.connector_code` = `psp_catalog.technical_id`) and applies the same legacy gates (lifecycle status, currency, GEO, capability, deposit stream, `merchant_providers`). The Route Target must belong to this merchant (`404 route_target_not_found` otherwise); combining it with `merchant_terminal_id` is `422 invalid_request`. An account-level route WITHOUT the binding cannot route traffic and is reported as `route_target_unbound`."
          },
          "transaction_type": {
            "type": "string",
            "enum": [
              "deposit",
              "payout"
            ],
            "default": "deposit"
          }
        }
      },
      "RoutingCascadeRoute": {
        "type": "object",
        "required": [
          "id",
          "cascade_id",
          "method_id",
          "priority",
          "weight"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "format": "int64"
          },
          "cascade_id": {
            "type": "integer",
            "format": "int64"
          },
          "merchant_terminal_id": {
            "type": "integer",
            "format": "int64",
            "nullable": true
          },
          "route_target_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "PA-137: the explicit Route Target of an ACCOUNT-level route (`merchant_terminal_id = null`); absent on a terminal-bound route, whose target comes from `merchant_terminals.route_target_id`."
          },
          "method_id": {
            "type": "string",
            "format": "uuid"
          },
          "priority": {
            "type": "integer"
          },
          "weight": {
            "type": "integer"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "PspCatalogEntry": {
        "type": "object",
        "required": [
          "id",
          "technical_id",
          "name",
          "integration_status",
          "terminal_policy",
          "environments",
          "created_at",
          "updated_at",
          "globally_disabled",
          "applies_to"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "technical_id": {
            "type": "string",
            "description": "Immutable link to `providers.connector_code`."
          },
          "name": {
            "type": "string"
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "logo_url": {
            "type": "string",
            "nullable": true
          },
          "integration_status": {
            "type": "string",
            "enum": [
              "DRAFT",
              "INTEGRATING",
              "ACTIVE",
              "DEPRECATED",
              "RETIRED"
            ]
          },
          "globally_disabled": {
            "type": "boolean",
            "default": false,
            "description": "PA-136 (M-1): the operator's GLOBAL availability kill switch (`POST /v1/psp-catalog/{id}/disable|enable`), orthogonal to `integration_status` (the definition lifecycle — an ACTIVE PSP may be disabled globally during an incident, a DRAFT one may be enabled). `true` = every merchant connection/route of this PSP evaluates as blocked (`effective_status`/routing-preview reason `psp_blocked`), enabling/restoring a connection answers `409 psp_disabled_globally`, and the connection detail carries the `psp_disabled_globally` warning. NOTHING is deleted: the flag is reversible and only stored in `psp_catalog.globally_disabled` (migration 0043)."
          },
          "terminal_policy": {
            "type": "string",
            "enum": [
              "NONE",
              "SHARED",
              "MULTIPLE"
            ]
          },
          "auth_scheme": {
            "type": "string",
            "nullable": true,
            "enum": [
              "private_key_only",
              "merchant_private",
              "basic",
              "api_key",
              "bearer",
              "oauth",
              "hmac",
              "custom"
            ]
          },
          "adapter_key": {
            "type": "string",
            "nullable": true
          },
          "version": {
            "type": "string",
            "nullable": true
          },
          "environments": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "sandbox",
                "live"
              ]
            }
          },
          "applies_to": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "string",
              "enum": [
                "payments",
                "payouts",
                "refunds"
              ]
            },
            "description": "PA-148 (migration 0049): the operations the API-auth scheme covers — a NON-EMPTY subset of `payments | payouts | refunds`, in operator order, duplicates removed. A real column of `psp_catalog` (`TEXT[] NOT NULL DEFAULT '{payments}'`), returned by BOTH read surfaces (list and detail) and by every write response. Definition configuration, not a routing decision: where a payment executes is decided by the merchant routing cascade."
          },
          "auth_header": {
            "type": "string",
            "nullable": true,
            "maxLength": 64,
            "pattern": "^[A-Za-z0-9-]+$",
            "description": "PA-148: name of the HTTP header carrying the signature/key of the API-auth scheme (`Authorization`, `X-Api-Key`, …). `null`/`\"\"` = not configured (the API normalizes an empty string to NULL); the DB CHECK repeats the pattern and the 64-char limit."
          },
          "signature_params": {
            "type": "string",
            "nullable": true,
            "maxLength": 128,
            "description": "PA-148: free-text description of what is included in the signature (`payload+timestamp`, …). `null`/`\"\"` = not configured; max 128 characters."
          },
          "methods": {
            "type": "array",
            "description": "PA-136 live-fix (W6): the PSP's GLOBAL method restrictions (`psp_methods`, one row per method + `transaction_type`) joined with the `payment_methods` dictionary. Populated by the two READ surfaces only — `GET /v1/psp-catalog` (ONE batched query for the whole page) and `GET /v1/psp-catalog/{id}` — so the catalog/routing/manage pages can render the methods of every PSP without an extra round-trip per PSP. Write responses (POST/PATCH, disable/enable, publish) OMIT the field, which therefore stays optional in this schema. Each item carries the UUID `method_id` the routing «Add Route» flow needs plus `method_code`/`method_name`/`method_category`/`transaction_type`/`currencies`/`countries`/`min_amount`/`max_amount`/`availability`.",
            "items": {
              "$ref": "#/components/schemas/PspMethod"
            }
          },
          "merchants_connected": {
            "type": "integer",
            "format": "int64",
            "minimum": 0,
            "description": "PA-139 (C12): number of DISTINCT merchants with a LIVE (non-archived) connection of this PSP. Populated by `GET /v1/psp-catalog` only (one batched aggregate per page, the exact predicate of `GET /v1/psp-catalog/{id}/impact`); every other surface omits the field, so those payloads stay unchanged."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "PspGlobalAvailabilityRequest": {
        "type": "object",
        "description": "Body of `POST /v1/psp-catalog/{id}/disable|enable` (PA-136 M-1). Every field is optional — an absent body is valid (the endpoints are idempotent and need no payload).",
        "properties": {
          "reason": {
            "type": "string",
            "maxLength": 500,
            "description": "Optional operator reason, recorded in the audit event only."
          }
        }
      },
      "PspGlobalImpactResponse": {
        "type": "object",
        "description": "Data footprint of one catalog PSP (`GET /v1/psp-catalog/{id}/impact`, PA-136 M-1): what the operator's global disable would switch off. Counters ONLY — never a record and never a credential.",
        "required": [
          "psp_id",
          "technical_id",
          "globally_disabled",
          "merchants",
          "connections",
          "terminals",
          "routes",
          "methods"
        ],
        "properties": {
          "psp_id": {
            "type": "string",
            "format": "uuid"
          },
          "technical_id": {
            "type": "string"
          },
          "globally_disabled": {
            "type": "boolean",
            "description": "The CURRENT state of the kill switch at impact-read time."
          },
          "merchants": {
            "type": "integer",
            "format": "int64",
            "description": "Distinct merchants with a LIVE connection to this PSP."
          },
          "connections": {
            "type": "integer",
            "format": "int64",
            "description": "LIVE (non-archived) merchant connections to this PSP."
          },
          "terminals": {
            "type": "integer",
            "format": "int64",
            "description": "LIVE (non-archived) terminals of those connections."
          },
          "routes": {
            "type": "integer",
            "format": "int64",
            "description": "Routing-cascade routes structurally bound to the PSP (route → terminal → connection). Account-level routes carry no PSP reference by design (ADR-0009 §6.1) and are not attributable to one PSP, so they are not counted."
          },
          "methods": {
            "type": "integer",
            "format": "int64",
            "description": "The PSP's method restriction rows (`psp_methods`)."
          }
        }
      },
      "UpdatePspCatalogRequest": {
        "type": "object",
        "description": "PATCH body: absent field = unchanged, explicit null clears a nullable field. `technical_id` is immutable and not accepted.",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 255
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "logo_url": {
            "type": "string",
            "nullable": true
          },
          "adapter_key": {
            "type": "string",
            "nullable": true,
            "maxLength": 255
          },
          "auth_scheme": {
            "type": "string",
            "nullable": true,
            "description": "Empty string clears the scheme.",
            "enum": [
              "private_key_only",
              "merchant_private",
              "basic",
              "api_key",
              "bearer",
              "oauth",
              "hmac",
              "custom",
              ""
            ]
          },
          "terminal_policy": {
            "type": "string",
            "enum": [
              "NONE",
              "SHARED",
              "MULTIPLE"
            ]
          },
          "version": {
            "type": "string",
            "nullable": true,
            "maxLength": 255
          },
          "environments": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "string",
              "enum": [
                "sandbox",
                "live"
              ]
            }
          },
          "applies_to": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "string",
              "enum": [
                "payments",
                "payouts",
                "refunds"
              ]
            },
            "description": "PA-148: REPLACES the scheme scope; an empty list is `422 invalid_applies_to` (`details.field = \"applies_to\"`) because a scheme covering no operation is meaningless. Absent = unchanged."
          },
          "auth_header": {
            "type": "string",
            "nullable": true,
            "maxLength": 64,
            "pattern": "^[A-Za-z0-9-]+$",
            "description": "PA-148: absent = unchanged; `null` or `\"\"` clears the header name. Anything outside `^[A-Za-z0-9-]+$` or longer than 64 is `422 invalid_auth_header` (`details.field = \"auth_header\"`)."
          },
          "signature_params": {
            "type": "string",
            "nullable": true,
            "maxLength": 128,
            "description": "PA-148: absent = unchanged; `null` or `\"\"` clears the signature text; longer than 128 characters is `422 invalid_signature_params` (`details.field = \"signature_params\"`)."
          },
          "integration_status": {
            "type": "string",
            "enum": [
              "DRAFT",
              "INTEGRATING",
              "ACTIVE",
              "DEPRECATED",
              "RETIRED"
            ]
          }
        }
      },
      "CredentialFieldDefinition": {
        "type": "object",
        "required": [
          "id",
          "scope",
          "is_secret",
          "key",
          "label",
          "field_type",
          "required",
          "position"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "terminal_template_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Parent of a `scope=terminal` field."
          },
          "psp_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Parent of the merchant_account/webhook/operation_specific fields."
          },
          "scope": {
            "type": "string",
            "enum": [
              "merchant_account",
              "terminal",
              "webhook",
              "operation_specific"
            ]
          },
          "key": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{1,63}$"
          },
          "label": {
            "type": "string"
          },
          "field_type": {
            "type": "string",
            "enum": [
              "text",
              "password",
              "multiline_secret",
              "pem",
              "multiline_text",
              "number",
              "boolean",
              "select",
              "json",
              "file_ref"
            ]
          },
          "required": {
            "type": "boolean"
          },
          "is_secret": {
            "type": "boolean"
          },
          "hint": {
            "type": "string",
            "nullable": true
          },
          "default_value": {
            "type": "string",
            "nullable": true,
            "description": "Non-secret default only; secret types may not carry one."
          },
          "placeholder": {
            "type": "string",
            "nullable": true
          },
          "validation": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true
          },
          "environment": {
            "type": "string",
            "nullable": true,
            "enum": [
              "sandbox",
              "live"
            ]
          },
          "select_options": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "object",
              "required": [
                "value"
              ],
              "properties": {
                "value": {
                  "type": "string"
                },
                "label": {
                  "type": "string"
                }
              },
              "additionalProperties": true
            }
          },
          "position": {
            "type": "integer",
            "format": "int32"
          }
        }
      },
      "CredentialFieldListResponse": {
        "type": "object",
        "required": [
          "fields"
        ],
        "properties": {
          "fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CredentialFieldDefinition"
            }
          }
        }
      },
      "CreateCredentialFieldRequest": {
        "type": "object",
        "required": [
          "key",
          "label",
          "field_type"
        ],
        "properties": {
          "scope": {
            "type": "string",
            "enum": [
              "merchant_account",
              "terminal",
              "webhook",
              "operation_specific"
            ],
            "default": "terminal"
          },
          "terminal_template_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "key": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{1,63}$"
          },
          "label": {
            "type": "string",
            "minLength": 1,
            "maxLength": 255
          },
          "field_type": {
            "type": "string",
            "enum": [
              "text",
              "password",
              "multiline_secret",
              "pem",
              "multiline_text",
              "number",
              "boolean",
              "select",
              "json",
              "file_ref"
            ]
          },
          "required": {
            "type": "boolean",
            "default": false
          },
          "is_secret": {
            "type": "boolean",
            "default": true
          },
          "hint": {
            "type": "string",
            "nullable": true
          },
          "placeholder": {
            "type": "string",
            "nullable": true
          },
          "validation": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true
          },
          "environment": {
            "type": "string",
            "nullable": true,
            "enum": [
              "sandbox",
              "live"
            ]
          },
          "default_value": {
            "type": "string",
            "nullable": true
          },
          "select_options": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "position": {
            "type": "integer",
            "format": "int32"
          }
        }
      },
      "UpdateCredentialFieldRequest": {
        "type": "object",
        "description": "PATCH body; `key`, `scope` and the parent are immutable and not accepted.",
        "properties": {
          "label": {
            "type": "string",
            "minLength": 1,
            "maxLength": 255
          },
          "field_type": {
            "type": "string",
            "enum": [
              "text",
              "password",
              "multiline_secret",
              "pem",
              "multiline_text",
              "number",
              "boolean",
              "select",
              "json",
              "file_ref"
            ]
          },
          "required": {
            "type": "boolean"
          },
          "is_secret": {
            "type": "boolean"
          },
          "hint": {
            "type": "string",
            "nullable": true
          },
          "placeholder": {
            "type": "string",
            "nullable": true
          },
          "validation": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true
          },
          "environment": {
            "type": "string",
            "nullable": true,
            "enum": [
              "sandbox",
              "live"
            ]
          },
          "default_value": {
            "type": "string",
            "nullable": true
          },
          "select_options": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "position": {
            "type": "integer",
            "format": "int32"
          }
        }
      },
      "ReorderCredentialFieldsRequest": {
        "type": "object",
        "required": [
          "field_ids"
        ],
        "properties": {
          "field_ids": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "uuid"
            }
          }
        }
      },
      "TerminalTemplate": {
        "type": "object",
        "required": [
          "id",
          "psp_id",
          "name",
          "allow_multiple",
          "min_instances",
          "created_at",
          "updated_at"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "psp_id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "code": {
            "type": "string",
            "nullable": true,
            "pattern": "^[A-Z][A-Z0-9_]{1,31}$",
            "description": "PA-143: operator-facing template code (UPPER_SNAKE, 2–32). Nullable — every template backfilled by migration 0038 (`legacy-default`) has none. Unique per PSP through the partial index `uq_terminal_templates_psp_code` (`WHERE code IS NOT NULL`); a duplicate answers `409 terminal_template_code_exists`."
          },
          "allow_multiple": {
            "type": "boolean"
          },
          "environment": {
            "type": "string",
            "enum": [
              "sandbox",
              "live",
              "both"
            ],
            "default": "both",
            "description": "PA-143: environment scope of the template (`terminal_templates.environment`, migration 0047). Closed TEXT+CHECK vocabulary; `both` is the column DEFAULT and therefore the behaviour of every pre-0047 row."
          },
          "min_instances": {
            "type": "integer",
            "format": "int32",
            "minimum": 1
          },
          "max_instances": {
            "type": "integer",
            "format": "int32",
            "nullable": true,
            "description": "null = unlimited"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "TerminalTemplateSummary": {
        "allOf": [
          {
            "$ref": "#/components/schemas/TerminalTemplate"
          },
          {
            "type": "object",
            "required": [
              "method_ids",
              "credential_field_count",
              "required_field_count",
              "terminals_count",
              "merchants_count"
            ],
            "properties": {
              "method_ids": {
                "type": "array",
                "items": {
                  "type": "string",
                  "format": "uuid"
                }
              },
              "methods": {
                "type": "array",
                "description": "PA-143: the same methods RESOLVED against `payment_methods`, ordered by code — `{id, code, name}`. The console renders the «Supported methods» chips from the codes; `method_ids` alone left that column empty.",
                "items": {
                  "type": "object",
                  "required": [
                    "id",
                    "code",
                    "name"
                  ],
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "code": {
                      "type": "string",
                      "description": "payment_methods.code (snake_case routing key)"
                    },
                    "name": {
                      "type": "string"
                    }
                  }
                }
              },
              "credential_field_count": {
                "type": "integer",
                "format": "int64"
              },
              "fields": {
                "type": "array",
                "description": "PA-143: the FULL credential schema of the template (`credential_field_definitions`, scope=terminal), ordered by `position, key`. The template drawer renders this list with Edit/Remove; `credential_field_count` stays for the table column.",
                "items": {
                  "$ref": "#/components/schemas/CredentialFieldDefinition"
                }
              },
              "required_field_count": {
                "type": "integer",
                "format": "int64"
              },
              "terminals_count": {
                "type": "integer",
                "format": "int64",
                "description": "PA-144: LIVE terminal instances of this template — the SERVER value behind the console's «терміналів: N» counter. Same predicate as `GET …/terminal-templates/{template_id}/terminals`: a live terminal of a live connection owned by a merchant of the calling tenant (archived terminals/connections are NOT counted), so the counter and the drill-down can never disagree."
              },
              "merchants_count": {
                "type": "integer",
                "format": "int64",
                "description": "PA-144: distinct merchants owning those live terminals."
              }
            }
          }
        ]
      },
      "TerminalTemplateListResponse": {
        "type": "object",
        "required": [
          "templates"
        ],
        "properties": {
          "templates": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/TerminalTemplateSummary"
            }
          }
        }
      },
      "CreateTerminalTemplateRequest": {
        "type": "object",
        "required": [
          "name"
        ],
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 255
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "code": {
            "type": "string",
            "nullable": true,
            "pattern": "^[A-Z][A-Z0-9_]{1,31}$",
            "description": "PA-143: operator code (UPPER_SNAKE, 2–32; normalised to upper case). Unique per PSP; a duplicate answers `409 terminal_template_code_exists`. Absent/empty = no code (legal)."
          },
          "environment": {
            "type": "string",
            "enum": [
              "sandbox",
              "live",
              "both"
            ],
            "default": "both",
            "description": "PA-143: environment scope. Absent = `both`. A foreign value answers `422 invalid_environment`."
          },
          "allow_multiple": {
            "type": "boolean",
            "default": false
          },
          "min_instances": {
            "type": "integer",
            "format": "int32",
            "default": 1,
            "minimum": 1
          },
          "max_instances": {
            "type": "integer",
            "format": "int32",
            "nullable": true
          },
          "method_ids": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "uuid"
            }
          }
        }
      },
      "UpdateTerminalTemplateRequest": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 255
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "code": {
            "type": "string",
            "nullable": true,
            "pattern": "^[A-Z][A-Z0-9_]{1,31}$",
            "description": "PA-143: `null` clears the code, an absent key leaves it unchanged. A duplicate of the same PSP answers `409 terminal_template_code_exists`; a malformed value answers `422 invalid_template_code` (`details.field = \"code\"`)."
          },
          "environment": {
            "type": "string",
            "enum": [
              "sandbox",
              "live",
              "both"
            ],
            "description": "PA-143: environment scope; absent = unchanged. A foreign value answers `422 invalid_environment` (`details.field = \"environment\"`)."
          },
          "allow_multiple": {
            "type": "boolean"
          },
          "min_instances": {
            "type": "integer",
            "format": "int32",
            "minimum": 1
          },
          "max_instances": {
            "type": "integer",
            "format": "int32",
            "nullable": true
          }
        }
      },
      "ReplaceTerminalTemplateMethodsRequest": {
        "type": "object",
        "required": [
          "method_ids"
        ],
        "properties": {
          "method_ids": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "uuid"
            }
          }
        }
      },
      "CreatePaymentMethodRequest": {
        "type": "object",
        "required": [
          "code",
          "name",
          "routing_category",
          "supported_operations"
        ],
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[A-Z][A-Z0-9_]{1,63}$",
            "description": "Normalized to UPPER_SNAKE; unique case-insensitively; immutable."
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 255,
            "description": "Unique case-insensitively."
          },
          "routing_category": {
            "type": "string",
            "enum": [
              "CARD",
              "APPLE_PAY",
              "GOOGLE_PAY",
              "OPEN_BANKING",
              "BANK_TRANSFER"
            ]
          },
          "supported_operations": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "string",
              "enum": [
                "deposit",
                "payout",
                "refund"
              ]
            }
          },
          "description": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "UpdatePaymentMethodRequest": {
        "type": "object",
        "description": "PATCH body; `code` and `routing_category` are immutable and not accepted.",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 255
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "supported_operations": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "string",
              "enum": [
                "deposit",
                "payout",
                "refund"
              ]
            }
          },
          "status": {
            "type": "string",
            "enum": [
              "ACTIVE",
              "DEPRECATED",
              "HIDDEN"
            ]
          }
        }
      },
      "DefinitionFinding": {
        "type": "object",
        "description": "One machine-checkable finding of a catalog PSP definition (PA-136 live-fix, W6). `code` is the STABLE identifier the Admin v2 UI keys its rendering on (never a human sentence); `path` points at the definition node the finding belongs to (`auth_scheme`, `methods[card:deposit].currencies`, `credential_fields[webhook]`, `terminal_templates[{id}]`, …); `message` is the operator-facing English sentence.",
        "required": [
          "code",
          "path",
          "message"
        ],
        "properties": {
          "code": {
            "type": "string",
            "description": "Stable finding code (see the `validate` endpoint for the full vocabulary)."
          },
          "path": {
            "type": "string",
            "description": "Path of the definition node the finding belongs to.",
            "example": "methods[card:deposit].currencies"
          },
          "message": {
            "type": "string",
            "description": "Operator-facing explanation."
          }
        }
      },
      "PspDefinitionValidation": {
        "type": "object",
        "description": "Result of `POST /v1/psp-catalog/{id}/validate` (PA-136 live-fix, W6). `ok` is `true` ONLY when `errors` is empty — that hard invariant is what the publish gate (`POST /v1/psp-catalog/{id}/publish`) relies on. `warnings` never block: they describe a definition that is usable but incomplete. Both lists are sorted by `(code, path)`.",
        "required": [
          "ok",
          "errors",
          "warnings"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "description": "`true` = no blocking errors (publish is allowed)."
          },
          "errors": {
            "type": "array",
            "description": "Blocking findings (`ok = false` while non-empty).",
            "items": {
              "$ref": "#/components/schemas/DefinitionFinding"
            }
          },
          "warnings": {
            "type": "array",
            "description": "Non-blocking findings.",
            "items": {
              "$ref": "#/components/schemas/DefinitionFinding"
            }
          }
        }
      },
      "ValidatePspDefinitionRequest": {
        "type": "object",
        "description": "Body of `POST /v1/psp-catalog/{id}/validate|publish` (PA-136 live-fix, W6). Every field is optional — an absent body is valid, `{}` is valid, and unknown keys are ignored (a future-proof scoping parameter would be additive).",
        "properties": {}
      },
      "UpdateMerchantRequest": {
        "type": "object",
        "description": "PA-140: the editable merchant profile. Every field is OPTIONAL (a partial update): an absent field keeps its stored value. Only these four fields are editable through `PATCH /v1/merchants/{id}`; API keys, webhook URL/secret, the h2h/payouts gates and the STD threshold have dedicated endpoints.",
        "minProperties": 1,
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 120,
            "description": "Trimmed; must not be empty after trimming. 1..120 characters."
          },
          "country": {
            "type": "string",
            "nullable": true,
            "description": "ISO 3166-1 alpha-2 (upper-cased). An explicit `null` clears the country; an absent field keeps it. An empty or blank string is `422 invalid_request` with `details.field=country` — the only reset spelling is `null`."
          },
          "currencies": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "maxItems": 50,
            "description": "Non-empty, duplicate-free ISO 4217 alpha-3 codes (upper-cased). At least one."
          },
          "legal_entity": {
            "type": "object",
            "nullable": true,
            "description": "Free-form legal-entity metadata (a JSON OBJECT). An explicit `null` clears it; an absent field keeps it."
          }
        }
      },
      "CatalogTerminalItem": {
        "type": "object",
        "required": [
          "merchant_id",
          "merchant_name",
          "terminal_id",
          "terminal_name",
          "status",
          "connection_id",
          "connection_status",
          "created_at"
        ],
        "properties": {
          "merchant_id": {
            "type": "string",
            "format": "uuid",
            "description": "Owner merchant id."
          },
          "merchant_name": {
            "type": "string",
            "description": "Owner merchant name(`merchants.name`)."
          },
          "terminal_id": {
            "type": "integer",
            "format": "int64",
            "description": "`merchant_terminals.id`."
          },
          "terminal_name": {
            "type": "string",
            "description": "Terminal instance name."
          },
          "status": {
            "type": "string",
            "enum": [
              "ENABLED",
              "DRAINING",
              "DEGRADED",
              "DISABLED"
            ],
            "description": "`merchant_terminals.status`."
          },
          "connection_id": {
            "type": "integer",
            "format": "int64",
            "description": "`merchant_psp_connections.id`."
          },
          "connection_status": {
            "type": "string",
            "description": "`merchant_psp_connections.status`: draft/enabled/available/blocked/hidden."
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "description": "RFC 3339 creation timestamp."
          },
          "route_target_id": {
            "type": "string",
            "format": "uuid",
            "description": "Present only when the terminal is bound to a Route Target."
          },
          "template_id": {
            "type": "string",
            "format": "uuid",
            "description": "PSP-wide list only: the template the terminal was created from."
          },
          "template_name": {
            "type": "string",
            "description": "PSP-wide list only: the template name."
          }
        }
      },
      "CatalogTerminalListResponse": {
        "type": "object",
        "required": [
          "terminals",
          "total"
        ],
        "properties": {
          "terminals": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CatalogTerminalItem"
            }
          },
          "total": {
            "type": "integer",
            "format": "int64",
            "description": "The UNPAGED population of the requested scope."
          }
        }
      },
      "UiVersion": {
        "type": "object",
        "required": [
          "admin_js_sha256"
        ],
        "properties": {
          "admin_js_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{16}$",
            "description": "First 16 hex characters of the SHA-256 of the served `admin.js`."
          }
        }
      },
      "ResendWebhookDeliveryRequest": {
        "type": "object",
        "description": "Body of `POST /v1/merchants/{id}/webhooks/deliveries/{delivery_id}/resend` (PA-149) — the ONE-OFF target of a manual re-send. The address is stored on the NEW delivery row only; the merchant's registered webhook endpoint is never changed.",
        "required": [
          "url"
        ],
        "properties": {
          "url": {
            "type": "string",
            "description": "The address THIS single re-send goes to. `http(s)`, at most 2048 characters, a non-empty host, no userinfo credentials; loopback/private/link-local/metadata hosts are rejected outside `dev`.",
            "maxLength": 2048,
            "example": "https://receiver.example.org/pa/webhook"
          },
          "event_id": {
            "type": "string",
            "description": "Optional `event_id` to deliver the re-send under (UNIQUE — an already-used id is `409 event_id_already_used`). Omitted → `<origin event_id>:resend:<uuid-v7>`.",
            "maxLength": 200,
            "example": "0192f0c4-6a1b-7c3d-8e9f-0a1b2c3d4e5f:resend:0192f0c4aa"
          }
        }
      }
    }
  }
}
