# =============================================================================
# WG Messaging Partner API - OpenAPI description
# Document revision : r3
# Created (UTC)     : 2026-11-04T18:08:47Z
# Last updated (UTC): 2026-11-04T18:45:00Z
# API version       : 0.3.1 (info.version tracks the API contract, not this file)
# Source            : docs/client-facing/partner-api-spec-20261104T081041Z.md
#                     (PR #76, merged; originally drafted from head b876bbe)
# Lint              : redocly lint -> valid, 0 errors, 1 warning (r3; info-license-strict wants a license url; one no-ambiguous-paths false positive suppressed in .redocly.lint-ignore.yaml)
#
# HOW TO UPDATE THIS FILE (do these in order)
#   1. BACK UP FIRST: copy this file to openapi.r<current-revision>.<UTC-timestamp>.yaml.bak
#      (for example openapi.r1.20261104T180847Z.yaml.bak) OUTSIDE the repo (never commit .bak files)
#      and keep it. Never edit without a backup.
#   2. Edit the YAML. The Markdown spec stays authoritative: change it first
#      (own PR), then mirror the change here.
#   3. Bump the revision (r1 -> r2 ...) and set "Last updated (UTC)" in this header
#      and in info.x-document below. Change info.version only if the API contract
#      version changes. Keep "Created (UTC)" as is.
#   4. Re-lint: npx @redocly/cli@latest lint openapi.yaml  (0 errors required).
#   5. Update the PR: branch avatra-dev/..., gh pr ready --undo (draft), commit with a
#      message naming the revision, push, update the PR body with the revision and
#      lint result, then gh pr ready. Read the posted body back to confirm it.
#   6. Never put real keys, tenant/workspace IDs, hosts or customer data in this file.
# =============================================================================
openapi: 3.0.3
info:
  title: WG Messaging Partner API
  version: 0.3.1
  license:
    name: Proprietary
  x-document:
    revision: r3
    created_at: '2026-11-04T18:08:47Z'
    updated_at: '2026-11-04T18:45:00Z'
    source: docs/client-facing/partner-api-spec-20261104T081041Z.md
    source_pr: 76
  description: |
    DRAFT derived from the client integration specification (PR #76, merged).
    The Markdown specification is authoritative; this file is a convenience and
    has not been validated against a running deployment.

    - `/partner/v1` is called with a workspace-scoped partner key (`pt_live_…`, `pt_test_…`).
    - `/management/v1` is called with a management credential (`mgmt_live_…`, `mgmt_test_…`)
      issued by the platform team. Both are backend-only; never use them from a browser.
    - Shapes the specification does not define are left as loose objects and marked as such.
    - A `202` on `POST /messages` means queued, not sent or delivered.
servers:
  - url: https://sway-synthesis-cosigner.ngrok-free.dev
    description: Development API endpoint supplied by Izu.

tags:
  - name: Connections
    description: 'Connected WhatsApp business numbers: list, inspect, health, capacity.'
  - name: Messages
    description: Send messages and read message status.
  - name: Media
    description: Upload and retrieve media.
  - name: Templates
    description: Message template management.
  - name: Webhooks
    description: Webhook endpoint configuration and signing secret.
  - name: Deliveries
    description: Webhook delivery log and replay.
  - name: Signup and lifecycle
    description: Embedded Signup sessions and connection lifecycle.
  - name: Management
    description: Management-key routes (/management/v1).
security:
  - partnerBearer: []
  - partnerKeyHeader: []
paths:
  /partner/v1/connections:
    get:
      tags: [Connections]
      operationId: listConnections
      summary: List active WhatsApp connections of the workspace
      description: Requires scope `connections:read`.
      responses:
        '200':
          description: Connections
          content:
            application/json:
              schema:
                type: object
                properties:
                  connections:
                    type: array
                    items: { $ref: '#/components/schemas/ConnectionSummary' }
        '401': { $ref: '#/components/responses/Error' }
        '403': { $ref: '#/components/responses/Error' }
        '429': { $ref: '#/components/responses/Error' }

  /partner/v1/messages:
    post:
      tags: [Messages]
      operationId: sendMessage
      summary: Queue an outbound message
      description: |
        Requires `messages:write`. Acceptance (`202`) means queued, not delivered.
        `recipient` is E.164 digits only (no `+`, spaces or dashes, at most 15 digits).
        The sender is chosen with `phone_number_id`; there is no fallback to another connection.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/SendMessageRequest' }
            examples:
              text:
                summary: Text message with quoted reply context
                value:
                  phone_number_id: <PHONE_NUMBER_ID>
                  recipient: <RECIPIENT_PHONE_NUMBER>
                  type: text
                  text: { body: Thank you for reaching out! Here is the order confirmation. }
                  context: { message_id: wamid.EXAMPLE }
              document:
                summary: Partner-hosted document
                value:
                  phone_number_id: <PHONE_NUMBER_ID>
                  recipient: <RECIPIENT_PHONE_NUMBER>
                  type: document
                  document:
                    link: https://example.invalid/document.pdf
                    filename: Invoice_October_2026.pdf
                    caption: Your monthly billing invoice
              template:
                summary: Approved template
                value:
                  phone_number_id: <PHONE_NUMBER_ID>
                  recipient: <RECIPIENT_PHONE_NUMBER>
                  type: template
                  template:
                    name: seasonal_promotion_2026
                    language: { code: en_US }
                    components:
                      - type: body
                        parameters:
                          - { type: text, text: Alex }
                          - { type: text, text: 25% OFF }
      responses:
        '202':
          description: Accepted (queued)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MessageAccepted' }
        '400': { $ref: '#/components/responses/Error' }
        '401': { $ref: '#/components/responses/Error' }
        '403': { $ref: '#/components/responses/Error' }
        '404': { $ref: '#/components/responses/Error' }
        '409':
          description: '`idempotency_conflict` or `idempotency_in_progress` (retry the same request and key after `Retry-After`)'
          headers:
            Retry-After: { $ref: '#/components/headers/RetryAfter' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '410': { $ref: '#/components/responses/Error' }
        '422': { $ref: '#/components/responses/Error' }
        '429': { $ref: '#/components/responses/Error' }
        '503': { $ref: '#/components/responses/Error' }

  /partner/v1/messages/{message_id}:
    get:
      tags: [Messages]
      operationId: getMessage
      summary: Get the lifecycle status of an outbound message
      description: Requires `messages:read`. Outbound messages only.
      parameters:
        - $ref: '#/components/parameters/MessageId'
      responses:
        '200':
          description: Message status
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MessageStatus' }
        '401': { $ref: '#/components/responses/Error' }
        '403': { $ref: '#/components/responses/Error' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/messages/{message_id}/cancel:
    post:
      tags: [Messages]
      operationId: cancelMessage
      summary: Cancel a queued message before transmission
      description: |
        Requires `messages:write`. Only `queued` messages can be cancelled. A message
        already being dispatched (`processing`) or completed returns `409 message_not_cancellable`.
        Also available as `POST /partner/v1/workspaces/{workspace_id}/messages/{message_id}/cancel`.
      parameters:
        - $ref: '#/components/parameters/MessageId'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: Cancelled (also returned if already cancelled)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CancelResult' }
        '404': { $ref: '#/components/responses/Error' }
        '409': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/messages/{message_id}/cancel:
    post:
      tags: [Messages]
      operationId: cancelMessageInWorkspace
      summary: Cancel a queued message (workspace-prefixed path)
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/MessageId'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: Cancelled
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CancelResult' }
        '404': { $ref: '#/components/responses/Error' }
        '409': { $ref: '#/components/responses/Error' }

  /partner/v1/media/{media_id}:
    get:
      tags: [Media]
      operationId: getMedia
      summary: Retrieve or stream an incoming customer media attachment
      description: |
        Requires `media:read`. `media_id` is the Meta media id exactly as it appears in the
        forwarded webhook payload. States: `available` (200/206), `pending` (409 `media_pending`),
        `blocked` (422 `policy_rejected`), `unavailable` (410 `media_unavailable`).
      parameters:
        - name: media_id
          in: path
          required: true
          schema: { type: string }
        - name: Range
          in: header
          required: false
          schema: { type: string, example: bytes=0-1048575 }
      responses:
        '200':
          description: Media bytes
          content:
            application/octet-stream:
              schema: { type: string, format: binary }
        '206':
          description: Partial content
          content:
            application/octet-stream:
              schema: { type: string, format: binary }
        '409':
          description: '`media_pending`'
          headers:
            Retry-After: { $ref: '#/components/headers/RetryAfter' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '410': { $ref: '#/components/responses/Error' }
        '416': { $ref: '#/components/responses/Error' }
        '422': { $ref: '#/components/responses/Error' }
        '503': { $ref: '#/components/responses/Error' }

  /partner/v1/media:
    post:
      tags: [Media]
      operationId: uploadMedia
      summary: Upload outbound media
      description: |
        Requires `media:write` or `messages:write`. Also available as
        `POST /partner/v1/workspaces/{workspace_id}/media`. Limits: audio 16 MiB, image 5 MiB,
        video 16 MiB, document 100 MiB. A media id is valid for 30 days and only for the
        workspace and connection that uploaded it.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/MediaUploadRequest' }
      responses:
        '201':
          description: Uploaded
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MediaUploadResult' }
        '409': { $ref: '#/components/responses/Error' }
        '413': { $ref: '#/components/responses/Error' }
        '415': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/media:
    post:
      tags: [Media]
      operationId: uploadMediaInWorkspace
      summary: Upload outbound media (workspace-prefixed path)
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/MediaUploadRequest' }
      responses:
        '201':
          description: Uploaded
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MediaUploadResult' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/connections/{connection_id}/templates:
    get:
      tags: [Templates]
      operationId: listTemplates
      summary: List message templates of a connection
      description: Requires `connections:read`. Defaults to `status=APPROVED`.
      parameters:
        - $ref: '#/components/parameters/ConnectionId'
        - name: status
          in: query
          required: false
          schema:
            type: string
            enum: [APPROVED, PENDING, REJECTED, PAUSED, DISABLED, all]
            default: APPROVED
      responses:
        '200':
          description: Templates
          content:
            application/json:
              schema:
                type: object
                properties:
                  templates:
                    type: array
                    items: { $ref: '#/components/schemas/Template' }
        '400': { $ref: '#/components/responses/Error' }
        '404': { $ref: '#/components/responses/Error' }
    post:
      tags: [Templates]
      operationId: createTemplate
      summary: Create a template
      description: Requires `templates:manage`.
      parameters:
        - $ref: '#/components/parameters/ConnectionId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TemplateCreateRequest' }
      responses:
        '201':
          description: Created (review pending)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Template' }
        '422': { $ref: '#/components/responses/Error' }
        '400': { $ref: '#/components/responses/Error' }
        '503': { $ref: '#/components/responses/Error' }

  /partner/v1/connections/{connection_id}/templates/{template}:
    delete:
      tags: [Templates]
      operationId: deleteTemplate
      summary: Delete a template by name
      description: Requires `templates:manage`. `language=all` deletes every language of the name.
      parameters:
        - $ref: '#/components/parameters/ConnectionId'
        - $ref: '#/components/parameters/TemplateRef'
        - name: language
          in: query
          required: true
          description: A language code (for example `en_US`) or `all`.
          schema: { type: string }
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  template_name: { type: string }
                  deleted: { type: boolean }
                  deleted_languages:
                    type: array
                    items: { type: string }
        '404': { $ref: '#/components/responses/Error' }
        '422': { $ref: '#/components/responses/Error' }
    put:
      tags: [Templates]
      operationId: updateTemplate
      summary: Update a template
      description: Requires `templates:manage`.
      parameters:
        - $ref: '#/components/parameters/ConnectionId'
        - $ref: '#/components/parameters/TemplateRef'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TemplateUpdateRequest' }
      responses:
        '200':
          description: Updated
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Template' }
        '404': { $ref: '#/components/responses/Error' }
        '422': { $ref: '#/components/responses/Error' }
        '400': { $ref: '#/components/responses/Error' }
        '503': { $ref: '#/components/responses/Error' }

  /partner/v1/connections/{connection_id}/templates/samples:
    post:
      tags: [Templates]
      operationId: createTemplateSample
      summary: Submit a review sample for a template
      description: Requires `templates:manage`.
      parameters:
        - $ref: '#/components/parameters/ConnectionId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [file_type, file_url]
              properties:
                file_type: { type: string, example: document }
                file_url: { type: string, format: uri, example: https://example.invalid/sample.pdf }
      responses:
        '201':
          description: Sample accepted
          content:
            application/json:
              schema:
                type: object
                properties:
                  sample_handle: { type: string }
                  file_type: { type: string }
                  size_bytes: { type: integer }
                  expires_at: { type: string, format: date-time }
        '422': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/webhook:
    put:
      tags: [Webhooks]
      operationId: putWebhook
      summary: Create or replace the workspace webhook
      description: |
        Requires `webhooks:manage`. HTTPS only, port 443, no userinfo, at most 2048 characters.
        A new or changed URL triggers a signed verification challenge. The signing secret is
        generated by the platform and returned once.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [webhook_url]
              properties:
                webhook_url: { type: string, format: uri, example: https://example.invalid/webhooks/wg }
                enabled: { type: boolean, default: true }
      responses:
        '200':
          description: Webhook configured
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookConfig' }
        '422': { $ref: '#/components/responses/Error' }
    get:
      tags: [Webhooks]
      operationId: getWebhook
      summary: Get webhook configuration and delivery health
      description: Requires `webhooks:manage`. The secret is never returned.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
      responses:
        '200':
          description: Webhook configuration
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookConfig' }
        '404': { $ref: '#/components/responses/Error' }
    delete:
      tags: [Webhooks]
      operationId: deleteWebhook
      summary: Remove the webhook subscription
      description: Requires `webhooks:manage`. WhatsApp connections are unaffected.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
      responses:
        '200':
          description: Removed
          content:
            application/json:
              schema:
                type: object
                properties:
                  workspace_id: { type: string }
                  webhook_url: { type: string, nullable: true }
                  enabled: { type: boolean }
                  cancelled_deliveries: { type: integer }
                  message: { type: string }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/webhook/secret/rotate:
    post:
      tags: [Webhooks]
      operationId: rotateWebhookSecret
      summary: Rotate the webhook signing secret
      description: |
        Requires `webhooks:manage`. `overlap_hours` 1 to 24 (default 24) signs deliveries with
        both secrets; `0` revokes the previous secret immediately.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                overlap_hours: { type: integer, minimum: 0, maximum: 24, default: 24 }
      responses:
        '200':
          description: Rotated; `signing_secret` returned once
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookConfig' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/webhook/verify:
    post:
      tags: [Webhooks]
      operationId: verifyWebhook
      summary: Start a new verification challenge
      description: Requires `webhooks:manage`. Response body is not specified in the client document.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
      responses:
        '200':
          description: Verification started (response shape not specified)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Unspecified' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/webhook/resume:
    post:
      tags: [Webhooks]
      operationId: resumeWebhook
      summary: Resume a paused endpoint after fixing it
      description: Requires `webhooks:manage`. Response body is not specified in the client document.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
      responses:
        '200':
          description: Resumed (response shape not specified)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Unspecified' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/deliveries:
    get:
      tags: [Deliveries]
      operationId: listDeliveries
      summary: List webhook deliveries
      description: Requires `events:read`. Cursor pagination. Response shape is not specified in the client document.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - name: status
          in: query
          schema:
            type: string
            enum: [pending, delivered, paused, rejected, exhausted, cancelled]
        - name: reason
          in: query
          description: For example `rejection_overflow`.
          schema: { type: string }
        - name: from
          in: query
          schema: { type: string, format: date-time }
        - name: to
          in: query
          schema: { type: string, format: date-time }
        - name: cursor
          in: query
          schema: { type: string }
      responses:
        '200':
          description: Deliveries (shape not specified)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Unspecified' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/deliveries/{delivery_id}:
    get:
      tags: [Deliveries]
      operationId: getDelivery
      summary: Delivery metadata (no body)
      description: Requires `events:read`. Response shape is not specified in the client document.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - name: delivery_id
          in: path
          required: true
          description: Delivery ID, opaque; always begins `del_`. Never the literal `replay`.
          schema: { type: string, pattern: '^del_[0-9a-f]{24,32}$', maxLength: 64, example: del_0123456789abcdef01234567 }
      responses:
        '200':
          description: Delivery metadata (shape not specified)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Unspecified' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/deliveries/{delivery_id}/replay:
    post:
      tags: [Deliveries]
      operationId: replayDelivery
      summary: Replay one delivery
      description: Requires `events:replay`. Response shape is not specified in the client document.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - name: delivery_id
          in: path
          required: true
          description: Delivery ID, opaque; always begins `del_`. Never the literal `replay`.
          schema: { type: string, pattern: '^del_[0-9a-f]{24,32}$', maxLength: 64, example: del_0123456789abcdef01234567 }
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: Replay requested (shape not specified)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Unspecified' }
        '410': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/deliveries/replay:
    post:
      tags: [Deliveries]
      operationId: replayDeliveries
      summary: Start a filtered batch replay job
      description: Requires `events:replay`.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                status: { type: string, enum: [exhausted, paused, rejected] }
                reason: { type: string, enum: [rejection_overflow] }
                from: { type: string, format: date-time }
                to: { type: string, format: date-time }
                limit: { type: integer, minimum: 1, maximum: 1000, default: 500 }
      responses:
        '202':
          description: Job accepted
          content:
            application/json:
              schema:
                type: object
                properties:
                  job_id: { type: string }
        '404': { $ref: '#/components/responses/Error' }

  # Lint note: Redocly's no-ambiguous-paths flags this against
  # .../deliveries/{delivery_id}/replay. It is a false positive: they differ in HTTP
  # method (GET vs POST) and IDs always carry a `job_`/`del_` prefix, so the only
  # overlapping URL, .../deliveries/replay/replay, is never a valid ID. The warning is
  # suppressed for this path only in .redocly.lint-ignore.yaml.
  /partner/v1/workspaces/{workspace_id}/deliveries/replay/{job_id}:
    get:
      tags: [Deliveries]
      operationId: getReplayJob
      summary: Replay job progress
      description: Requires `events:read` or `events:replay`.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - name: job_id
          in: path
          required: true
          description: Replay job ID, opaque; always begins `job_`, as returned by `POST …/deliveries/replay`.
          schema: { type: string, pattern: '^job_[0-9a-f]{24}$', maxLength: 64, example: job_0123456789abcdef01234567 }
      responses:
        '200':
          description: Job progress
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ReplayJob' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/signup/session:
    post:
      tags: [Signup and lifecycle]
      operationId: createSignupSession
      summary: Create an Embedded Signup (or reconnect) session
      description: |
        Requires `signup:manage` for `purpose: signup`; `connections:manage` (or `signup:manage`)
        for `purpose: reconnect`. A session expires in 15 minutes. Only one `signup` session may be
        open per workspace (`409 signup_session_state_invalid` with `details.session_id`).
        `signup_url` is NOT returned. Browser signup is intended to use the hosted onboarding
        gateway (stage/preview; production qualification pending); see the specification, 4.10.14.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                purpose: { type: string, enum: [signup, reconnect], default: signup }
                connection_id: { type: string, description: 'Required when purpose is reconnect.' }
                redirect_uri: { type: string, format: uri, maxLength: 2048, description: 'HTTPS, no userinfo.' }
      responses:
        '201':
          description: Session created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SignupSession' }
        '409': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/signup/complete:
    post:
      tags: [Signup and lifecycle]
      operationId: completeSignup
      summary: Complete a self-hosted Embedded Signup with a Meta authorization code
      description: |
        Requires `signup:manage`. Not used with the hosted onboarding gateway. A session accepts
        exactly one `code`; a failed exchange needs a fresh code and a new Idempotency-Key.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [session_id, code]
              properties:
                session_id: { type: string }
                code: { type: string }
                pin: { type: string, pattern: '^[0-9]{6}$', description: Optional two-step verification PIN. }
      responses:
        '200':
          description: Connected, PIN required or partially registered
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SignupOutcome' }
        '404': { $ref: '#/components/responses/Error' }
        '409': { $ref: '#/components/responses/Error' }
        '410': { $ref: '#/components/responses/Error' }
        '422': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/signup/{session_id}:
    get:
      tags: [Signup and lifecycle]
      operationId: getSignupSession
      summary: Read a signup session (authoritative result)
      description: |
        Requires `signup:manage` (`connections:manage` for a reconnect session). Browser or popup
        messages are never proof of a connection; use this read.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/SessionId'
      responses:
        '200':
          description: Session state
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SignupSessionState' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/signup/{session_id}/resume:
    post:
      tags: [Signup and lifecycle]
      operationId: resumeSignup
      summary: Resume a session in awaiting_pin or partial (no new code)
      description: Requires `signup:manage`. `pin` is required in `awaiting_pin` and ignored in `partial`.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/SessionId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                pin: { type: string, pattern: '^[0-9]{6}$' }
      responses:
        '200':
          description: Connected, PIN required or partially registered
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SignupOutcome' }
        '409': { $ref: '#/components/responses/Error' }
        '410': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/signup/{session_id}/cancel:
    post:
      tags: [Signup and lifecycle]
      operationId: cancelSignup
      summary: Abandon a session
      description: Requires `signup:manage` (`connections:manage` for a reconnect session). Naturally idempotent.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/SessionId'
      responses:
        '200':
          description: Session state after cancel
          content:
            application/json:
              schema:
                type: object
                properties:
                  session_id: { type: string }
                  state: { type: string }
        '409': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/connections/{connection_id}:
    get:
      tags: [Signup and lifecycle]
      operationId: getConnection
      summary: Details and health summary of one connection
      description: Requires `connections:read` or `connections:manage`.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/ConnectionId'
      responses:
        '200':
          description: Connection
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectionDetail' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/connections/{connection_id}/reconnect:
    post:
      tags: [Signup and lifecycle]
      operationId: reconnectConnection
      summary: Re-authorize one existing connection
      description: |
        Requires `connections:manage`. Needs a `reconnect` session created for the same connection.
        A different phone number or WABA is never swapped in (`409 connection_identity_mismatch`).
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/ConnectionId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [session_id, code]
              properties:
                session_id: { type: string }
                code: { type: string }
                expected_phone_number_id: { type: string, example: <PHONE_NUMBER_ID> }
      responses:
        '200':
          description: Reconnected
          content:
            application/json:
              schema:
                type: object
                properties:
                  connection_id: { type: string }
                  workspace_id: { type: string }
                  phone_number_id: { type: string }
                  status: { type: string }
                  reconnected: { type: boolean }
        '409': { $ref: '#/components/responses/Error' }
        '422': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/connections/{connection_id}/disconnect:
    post:
      tags: [Signup and lifecycle]
      operationId: disconnectConnection
      summary: Disconnect one connection
      description: |
        Requires `connections:manage`. Queued untransmitted messages for this connection become
        `cancelled`; in-flight messages complete. Idempotent.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/ConnectionId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                deregister: { type: boolean, default: true }
      responses:
        '200':
          description: Disconnected
          content:
            application/json:
              schema:
                type: object
                properties:
                  connection_id: { type: string }
                  workspace_id: { type: string }
                  status: { type: string, example: disconnected }
                  meta_deregistered: { type: boolean }
                  cancelled_queued_messages: { type: integer }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/connections/{connection_id}/health:
    get:
      tags: [Signup and lifecycle]
      operationId: getConnectionHealth
      summary: Connection health (credentials, permissions, phone, webhook)
      description: Requires `connections:read` or `connections:manage`.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/ConnectionId'
      responses:
        '200':
          description: Health
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectionHealth' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/connections/{connection_id}/capacity:
    get:
      tags: [Signup and lifecycle]
      operationId: getConnectionCapacity
      summary: Rolling 24-hour unique-recipient capacity
      description: |
        Requires `connections:read` or `connections:manage`. Local capacity enforcement is
        best-effort; Meta's own enforcement still applies.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/ConnectionId'
        - name: fresh
          in: query
          description: '`true` forces an immediate refresh of the messaging tier from Meta.'
          schema: { type: boolean }
      responses:
        '200':
          description: Capacity
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectionCapacity' }
        '404': { $ref: '#/components/responses/Error' }

  /partner/v1/workspaces/{workspace_id}/connections/{connection_id}/webhook/subscribe:
    post:
      tags: [Signup and lifecycle]
      operationId: subscribeConnectionWebhook
      summary: Re-subscribe or repair the Meta webhook subscription
      description: Requires `connections:manage`. No request body.
      parameters:
        - $ref: '#/components/parameters/WorkspaceId'
        - $ref: '#/components/parameters/ConnectionId'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: Subscribed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectionDetail' }
        '422': { $ref: '#/components/responses/Error' }

  /management/v1/tenants/provision:
    post:
      tags: [Management]
      operationId: provisionTenant
      summary: Provision or link an external workspace to a messaging workspace
      description: |
        Management credential with scope `tenants:provision`. `environment` must equal the
        credential's environment. 201 for a new tenant, 200 for an existing identical link.
      security:
        - mgmtBearer: []
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [external_workspace_id, name, environment]
              properties:
                external_workspace_id: { type: string }
                name: { type: string }
                environment: { type: string, enum: [live, sandbox] }
      responses:
        '200':
          description: Existing link
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Tenant' }
        '201':
          description: New tenant
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Tenant' }
        '409': { $ref: '#/components/responses/Error' }
        '422': { $ref: '#/components/responses/Error' }

  /management/v1/tenants/{tenant_id}/credentials:
    post:
      tags: [Management]
      operationId: issueCredential
      summary: Issue a scoped partner key (also the rotate operation)
      description: |
        Management credential with scope `tenants:provision`. A principal may hold at most two
        active keys (`409 credential_limit_reached`). The plaintext `key` is returned in the 201
        and, for 24 hours, on an identical replay; after that a replay returns 200 with
        `key_recoverable: false`.
      security:
        - mgmtBearer: []
      parameters:
        - name: tenant_id
          in: path
          required: true
          schema: { type: string }
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, scopes]
              properties:
                name: { type: string }
                scopes:
                  type: array
                  items: { $ref: '#/components/schemas/PartnerScope' }
                expires_in_days: { type: integer, example: 365 }
      responses:
        '201':
          description: Issued
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IssuedCredential' }
        '200':
          description: Replay after the 24-hour window (key omitted)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IssuedCredential' }
        '409': { $ref: '#/components/responses/Error' }

  /management/v1/tenants/{tenant_id}/credentials/{lookup_id}:
    delete:
      tags: [Management]
      operationId: revokeCredential
      summary: Revoke a partner key
      description: Management credential with scope `tenants:provision`. Idempotent.
      security:
        - mgmtBearer: []
      parameters:
        - name: tenant_id
          in: path
          required: true
          schema: { type: string }
        - name: lookup_id
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Revoked
          content:
            application/json:
              schema:
                type: object
                properties:
                  lookup_id: { type: string }
                  status: { type: string, example: revoked }
                  revoked_at: { type: string, format: date-time }
        '404': { $ref: '#/components/responses/Error' }

components:
  securitySchemes:
    partnerBearer:
      type: http
      scheme: bearer
      description: Partner key (`pt_live_…` or `pt_test_…`).
    partnerKeyHeader:
      type: apiKey
      in: header
      name: X-Partner-Key
      description: Alternative to the Authorization header for the partner key.
    mgmtBearer:
      type: http
      scheme: bearer
      description: Management credential (`mgmt_live_…` or `mgmt_test_…`). Accepted only on `/management/v1`.
  parameters:
    TemplateRef:
      name: template
      in: path
      required: true
      description: Template ID for update; template name for delete.
      schema: { type: string }
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: 1 to 255 characters from `A-Z a-z 0-9 _ - . :`. A UUID is recommended.
      schema: { type: string, minLength: 1, maxLength: 255 }
    WorkspaceId:
      name: workspace_id
      in: path
      required: true
      description: Must equal the credential's workspace, otherwise `404 resource_not_found`.
      schema: { type: string, example: ws_8f9a2b1c4d }
    ConnectionId:
      name: connection_id
      in: path
      required: true
      schema: { type: string, example: conn_5a2b1c }
    MessageId:
      name: message_id
      in: path
      required: true
      schema: { type: string, example: msg_01j7b5c3d2e1f0a9 }
    SessionId:
      name: session_id
      in: path
      required: true
      schema: { type: string, example: ses_9a1b2c3d4e }
  headers:
    RetryAfter:
      description: Seconds to wait before retrying.
      schema: { type: integer }
  responses:
    Error:
      description: Error envelope. Branch on `error.code`; `message` text is illustrative.
      headers:
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
        X-Request-Id:
          schema: { type: string }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
  schemas:
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message, request_id, retryable]
          properties:
            code:
              type: string
              description: |
                Stable machine-readable code, for example invalid_request, invalid_credential,
                insufficient_scope, resource_not_found, idempotency_conflict, idempotency_in_progress,
                message_not_cancellable, signup_session_state_invalid, phone_number_conflict,
                connection_identity_mismatch, tenant_conflict, credential_limit_reached, media_pending,
                media_unavailable, signup_session_expired, content_expired, payload_too_large,
                unsupported_media_type, range_not_satisfiable, policy_rejected, unsupported_capability,
                connection_unavailable, payment_required, template_not_found, media_url_rejected,
                webhook_url_rejected, signup_code_rejected, signup_pin_attempts_exceeded,
                template_rejected, sample_rejected, rate_limited, quota_exceeded, internal_error,
                temporarily_unavailable.
            message: { type: string }
            request_id: { type: string }
            retryable: { type: boolean }
            details: { type: object, additionalProperties: true }
    Unspecified:
      type: object
      additionalProperties: true
      description: Shape not specified in the client document.
    PartnerScope:
      type: string
      enum:
        - connections:read
        - connections:manage
        - messages:write
        - messages:read
        - media:read
        - media:write
        - webhooks:manage
        - events:read
        - events:replay
        - signup:manage
        - templates:manage
    ConnectionSummary:
      type: object
      properties:
        connection_id: { type: string }
        phone_number_id: { type: string }
        display_phone_number: { type: string }
        verified_name: { type: string }
        quality_rating: { type: string, example: GREEN }
        status: { type: string, example: active }
        created_at: { type: string, format: date-time }
        marketing_messages_supported: { type: boolean }
        marketing_messages_qualification_status: { type: string }
    ConnectionDetail:
      type: object
      properties:
        connection_id: { type: string }
        workspace_id: { type: string }
        waba_id: { type: string }
        phone_number_id: { type: string }
        display_phone_number: { type: string }
        verified_name: { type: string }
        status: { type: string, example: connected }
        quality_rating: { type: string }
        messaging_limit_tier: { type: string, example: TIER_10K }
        webhook_subscribed: { type: boolean }
        last_synced_at: { type: string, format: date-time }
        marketing_messages_supported: { type: boolean }
        marketing_messages_qualification_status: { type: string }
    ConnectionHealth:
      type: object
      properties:
        connection_id: { type: string }
        workspace_id: { type: string }
        status: { type: string, enum: [healthy, degraded, expired, unregistered] }
        checked_at: { type: string, format: date-time, nullable: true }
        reasons:
          type: array
          items: { type: string, description: 'For example webhook_unsubscribed, quality_degraded, stale_evidence, provider_unreachable.' }
        credentials: { type: object, additionalProperties: true }
        permissions: { type: object, additionalProperties: true }
        phone: { type: object, additionalProperties: true }
        webhook: { type: object, additionalProperties: true }
        is_stale: { type: boolean }
    ConnectionCapacity:
      type: object
      properties:
        connection_id: { type: string }
        workspace_id: { type: string }
        phone_number_id: { type: string }
        tier: { type: string, example: TIER_1K }
        limit_24h: { type: integer }
        used_24h: { type: integer }
        remaining_24h: { type: integer }
        rolling_window_seconds: { type: integer, example: 86400 }
        oldest_slot_expires_at: { type: string, format: date-time, nullable: true }
        status: { type: string, enum: [available, exhausted] }
        deferral:
          type: object
          nullable: true
          properties:
            reason: { type: string, example: messaging_limit_reached }
            next_eligible_at: { type: string, format: date-time }
        tier_synced_at: { type: string, format: date-time, nullable: true }
        tier_stale: { type: boolean }
        checked_at: { type: string, format: date-time }
    SendMessageRequest:
      type: object
      required: [phone_number_id, recipient, type]
      properties:
        phone_number_id: { type: string, example: <PHONE_NUMBER_ID> }
        recipient: { type: string, example: <RECIPIENT_PHONE_NUMBER>, description: 'E.164 digits only, at most 15.' }
        type:
          type: string
          enum: [text, image, video, audio, document, sticker, template]
        text:
          type: object
          properties:
            body: { type: string }
        image: { $ref: '#/components/schemas/MediaRef' }
        video: { $ref: '#/components/schemas/MediaRef' }
        audio: { $ref: '#/components/schemas/MediaRef' }
        document: { $ref: '#/components/schemas/MediaRef' }
        sticker: { $ref: '#/components/schemas/MediaRef' }
        template:
          type: object
          required: [name, language]
          properties:
            name: { type: string }
            language:
              type: object
              properties:
                code: { type: string, example: en_US }
            components:
              type: array
              items: { type: object, additionalProperties: true }
        context:
          type: object
          description: Quoted reply context.
          properties:
            message_id: { type: string }
        expires_at:
          type: string
          format: date-time
          description: RFC 3339 with an explicit offset; must be in the future.
        expiry_guarantee:
          type: string
          enum: [stop_dispatch, provider_validity]
          description: Requires expires_at. `provider_validity` applies to marketing template messages only.
    MediaRef:
      type: object
      properties:
        link: { type: string, format: uri, description: Public HTTPS URL of partner-hosted media. }
        id: { type: string, description: Media id from POST /media. }
        filename: { type: string }
        caption: { type: string }
    MessageAccepted:
      type: object
      properties:
        message_id: { type: string }
        correlation_id: { type: string }
        status: { type: string, example: queued }
        phone_number_id: { type: string }
        recipient: { type: string }
        expires_at: { type: string, format: date-time }
        expiry_guarantee: { type: string }
        created_at: { type: string, format: date-time }
    MessageStatus:
      type: object
      properties:
        message_id: { type: string }
        correlation_id: { type: string }
        status:
          type: string
          enum: [queued, sent, delivered, read, outcome_unknown, failed, cancelled, expired]
        provider_message_id: { type: string, nullable: true, description: Meta wamid. }
        phone_number_id: { type: string }
        recipient: { type: string }
        type: { type: string }
        pricing:
          type: object
          nullable: true
          properties:
            category: { type: string }
            pricing_model: { type: string }
        timestamps:
          type: object
          properties:
            queued_at: { type: string, format: date-time, nullable: true }
            sent_at: { type: string, format: date-time, nullable: true }
            delivered_at: { type: string, format: date-time, nullable: true }
            read_at: { type: string, format: date-time, nullable: true }
        error: { type: object, nullable: true, additionalProperties: true }
        conflicting_evidence:
          type: array
          items: { type: object, additionalProperties: true }
        expiry:
          type: object
          description: Present only when the message was sent with expires_at.
          properties:
            expires_at: { type: string, format: date-time }
            guarantee: { type: string }
            dispatch_cutoff_at: { type: string, format: date-time }
            cutoff_basis: { type: string, enum: [expires_at, queue_deadline, provider_validity] }
            provider_validity_seconds: { type: integer, nullable: true }
            safety_margin_seconds: { type: integer }
    CancelResult:
      type: object
      properties:
        message_id: { type: string }
        status: { type: string, example: cancelled }
        cancelled_at: { type: string, format: date-time }
        phone_number_id: { type: string }
        recipient: { type: string }
    MediaUploadRequest:
      type: object
      required: [file_base64, mime_type]
      properties:
        file_base64: { type: string, format: byte }
        mime_type: { type: string, example: image/jpeg }
        filename: { type: string }
        connection_id: { type: string, description: Required if the workspace has several active connections. }
        phone_number_id: { type: string }
    MediaUploadResult:
      type: object
      properties:
        media_id: { type: string }
        mime_type: { type: string }
        size: { type: integer }
        expires_at: { type: string, format: date-time }
    Template:
      type: object
      properties:
        template_id: { type: string }
        name: { type: string }
        language: { type: string, example: en_US }
        category: { type: string, enum: [MARKETING, UTILITY, AUTHENTICATION] }
        status: { type: string, enum: [APPROVED, PENDING, REJECTED, PAUSED, DISABLED] }
        rejected_reason: { type: string }
        quality_score:
          type: object
          properties:
            score: { type: string, example: GREEN }
        message_send_ttl_seconds: { type: integer, description: 'MARKETING templates only, when set and accepted by Meta.' }
        message_send_ttl_unconfirmed_seconds: { type: integer }
        components:
          type: array
          items: { type: object, additionalProperties: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
    TemplateCreateRequest:
      type: object
      required: [name, category, language, components]
      properties:
        name: { type: string, example: shipping_update_v2 }
        category: { type: string, enum: [MARKETING, UTILITY, AUTHENTICATION] }
        language: { type: string, example: en_US }
        components:
          type: array
          items: { type: object, additionalProperties: true }
        message_send_ttl_seconds:
          type: integer
          minimum: 43200
          maximum: 2592000
          description: >-
            Optional provider delivery validity in seconds (43200 to 2592000), MARKETING templates only.
            A value on a UTILITY or AUTHENTICATION template, or outside the range, returns
            `422 invalid_request` with `details.field = message_send_ttl_seconds`; nothing is sent to Meta.
            If the outcome is unknown (timeout, `5xx`, lost connection) the call returns a retryable
            `503 temporarily_unavailable`; retry with the same `Idempotency-Key`. Omitting it changes nothing.
    TemplateUpdateRequest:
      type: object
      required: [components]
      description: >-
        Edits one template (a single language). `name` and `language` cannot be changed; sending them
        returns `400 invalid_request`.
      properties:
        category: { type: string, enum: [MARKETING, UTILITY, AUTHENTICATION] }
        components:
          type: array
          minItems: 1
          items: { type: object, additionalProperties: true }
        message_send_ttl_seconds:
          type: integer
          minimum: 43200
          maximum: 2592000
          description: >-
            Optional provider delivery validity in seconds (43200 to 2592000), MARKETING templates only. When `category` is omitted, the template's existing category is used and must be MARKETING.
            A value on a UTILITY or AUTHENTICATION template, or outside the range, returns
            `422 invalid_request` with `details.field = message_send_ttl_seconds`; nothing is sent to Meta.
            If the outcome is unknown (timeout, `5xx`, lost connection) the call returns a retryable
            `503 temporarily_unavailable`; retry with the same `Idempotency-Key`. Omitting it changes nothing.
    WebhookConfig:
      type: object
      properties:
        workspace_id: { type: string }
        webhook_url: { type: string, nullable: true }
        enabled: { type: boolean }
        verification_status: { type: string, enum: [pending, verified, failed] }
        secret_configured: { type: boolean }
        signing_secret: { type: string, description: 'Returned once, on creation or rotation only.' }
        secret_version: { type: integer }
        previous_secret_expires_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time }
        health:
          type: object
          properties:
            status: { type: string, enum: [healthy, degraded, unverified, paused, disabled] }
            consecutive_failures: { type: integer }
            last_successful_delivery: { type: string, format: date-time, nullable: true }
            pending_deliveries: { type: integer }
            paused_deliveries: { type: integer }
            rejected_deliveries: { type: integer }
            rejection_overflow_deliveries: { type: integer }
            oldest_waiting_age_seconds: { type: integer, nullable: true }
            circuit_state: { type: string, example: closed }
            dropped_events: { type: integer }
    ReplayJob:
      type: object
      properties:
        job_id: { type: string }
        workspace_id: { type: string }
        status: { type: string, enum: [queued, running, completed, failed] }
        counters:
          type: object
          properties:
            replayed: { type: integer }
            skipped: { type: integer }
            failed: { type: integer }
        replayed: { type: integer }
        skipped: { type: integer }
        failed: { type: integer }
        total: { type: integer }
        created_at: { type: string, format: date-time }
        started_at: { type: string, format: date-time, nullable: true }
        completed_at: { type: string, format: date-time, nullable: true }
    SignupSession:
      type: object
      properties:
        session_id: { type: string }
        workspace_id: { type: string }
        purpose: { type: string, enum: [signup, reconnect] }
        state: { type: string, example: created }
        app_id: { type: string, example: <META_APP_ID>, description: Only needed for the self-hosted flow. }
        config_id: { type: string, example: <SIGNUP_CONFIG_ID>, description: Only needed for the self-hosted flow. }
        expires_at: { type: string, format: date-time }
    SignupSessionState:
      type: object
      properties:
        session_id: { type: string }
        workspace_id: { type: string }
        purpose: { type: string, enum: [signup, reconnect] }
        state:
          type: string
          enum: [created, exchanging, awaiting_pin, partial, completed, cancelled, expired, failed]
        completed_steps:
          type: array
          items: { type: string }
        failed_step: { type: string, nullable: true }
        connection_id: { type: string, nullable: true }
        expires_at: { type: string, format: date-time }
        error:
          type: object
          nullable: true
          additionalProperties: true
    SignupOutcome:
      type: object
      description: One of connected, pin_required or registration_incomplete (discriminate on `status`).
      properties:
        status: { type: string, enum: [connected, pin_required, registration_incomplete] }
        connection_id: { type: string, nullable: true }
        workspace_id: { type: string }
        waba_id: { type: string }
        phone_number_id: { type: string }
        display_phone_number: { type: string }
        verified_name: { type: string }
        meta_registered: { type: boolean }
        session_id: { type: string }
        state: { type: string }
        pin_attempts_remaining: { type: integer }
        completed_steps:
          type: array
          items: { type: string }
        failed_step: { type: string, enum: [phone_registration, webhook_subscription, connection_binding] }
        retryable: { type: boolean }
        message: { type: string }
    Tenant:
      type: object
      properties:
        tenant_id: { type: string, example: ws_8f9a2b1c4d }
        external_workspace_id: { type: string }
        name: { type: string }
        environment: { type: string, enum: [live, sandbox] }
        status: { type: string, example: active }
        created_at: { type: string, format: date-time }
    IssuedCredential:
      type: object
      properties:
        lookup_id: { type: string, example: key_7c9e1234 }
        name: { type: string }
        tenant_id: { type: string }
        environment: { type: string }
        scopes:
          type: array
          items: { $ref: '#/components/schemas/PartnerScope' }
        key: { type: string, description: Shown once (see replay window). Omitted after 24 hours. }
        key_recoverable: { type: boolean }
        expires_at: { type: string, format: date-time }
