openapi: 3.0.3
info:
  title: ComRaid Public API
  version: "1.0"
  description: |
    Unversioned public product API for api.comraid.io.
    Authenticate with a project-scoped Bearer API key except:
    - delivery acknowledgement endpoints, which verify `attribution_token` against the delivery row
    - mobile SDK endpoints, which use the publishable `X-ComRaid-App-Id` header (`cr_app_...`)
    - `/healthz` and `/readyz`, which are unauthenticated operator probes

    Dashboard session routes under `/dashboard/*` are intentionally omitted from this
    specification — they are not a supported product integration surface.
servers:
  - url: https://api.comraid.io
    description: Production
  - url: http://localhost:8080
    description: Local
security:
  - bearerAuth: []
tags:
  - name: Contacts
  - name: Endpoints
  - name: Messages
  - name: Campaigns
  - name: Segments
  - name: Media
  - name: Deliveries
  - name: Mobile
  - name: Ops
paths:
  /healthz:
    get:
      tags: [Ops]
      summary: Liveness probe
      operationId: healthz
      security: []
      responses:
        "200":
          description: Process is up
          content:
            application/json:
              schema:
                type: object
                properties:
                  status: { type: string, example: ok }
  /readyz:
    get:
      tags: [Ops]
      summary: Readiness probe
      operationId: readyz
      security: []
      responses:
        "200":
          description: Postgres (and Redis when configured) are reachable
          content:
            application/json:
              schema:
                type: object
                properties:
                  status: { type: string, example: ready }
        "503":
          $ref: "#/components/responses/Error"

  /contacts:
    post:
      tags: [Contacts]
      summary: Create contact
      operationId: createContact
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ContactCreate"
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          $ref: "#/components/responses/Error"

  /contacts/{external_user_id}:
    put:
      tags: [Contacts]
      summary: Upsert contact
      operationId: upsertContact
      parameters:
        - $ref: "#/components/parameters/ExternalUserId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ContactUpsert"
      responses:
        "200":
          description: Upserted
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /contacts/{external_user_id}/attributes:
    put:
      tags: [Contacts]
      summary: Upsert contact attributes
      operationId: upsertContactAttributes
      parameters:
        - $ref: "#/components/parameters/ExternalUserId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [attributes]
              properties:
                attributes:
                  type: object
                  additionalProperties: true
                  description: |
                    Free-form Customer-supplied Attribute key/value pairs (prefer PUT /contacts/{external_user_id} with attributes).
                    Keys must be non-empty and ≤ 128 characters; values ≤ 4KB serialized; at most 200 keys per Contact.
                    A JSON `null` value removes that Attribute.
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactResponse"
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "413":
          $ref: "#/components/responses/Error"

  /contacts/{external_user_id}/preferences:
    get:
      tags: [Contacts]
      summary: List communication preferences
      operationId: listContactPreferences
      parameters:
        - $ref: "#/components/parameters/ExternalUserId"
      responses:
        "200":
          description: Preferences
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactPreferencesResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
    put:
      tags: [Contacts]
      summary: Upsert communication preferences
      operationId: upsertContactPreferences
      parameters:
        - $ref: "#/components/parameters/ExternalUserId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ContactPreferencesRequest"
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactPreferencesResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /contacts/{external_user_id}/opt-outs:
    get:
      tags: [Contacts]
      summary: List Channel opt-outs for a Contact
      operationId: listContactOptOuts
      parameters:
        - $ref: "#/components/parameters/ExternalUserId"
      responses:
        "200":
          description: Opt-outs
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactOptOutsResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"

  /contacts/{external_user_id}/opt-outs/{channel}:
    put:
      tags: [Contacts]
      summary: Set or clear Opted out for a Channel
      description: >
        Opted out is a hard gate per Contact per Channel. Setting opted_out true
        records the opt-out; false clears it (opt-in). Only push is supported in V1.
      operationId: putContactChannelOptOut
      parameters:
        - $ref: "#/components/parameters/ExternalUserId"
        - name: channel
          in: path
          required: true
          schema:
            type: string
            enum: [push]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ContactOptOutRequest"
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactOptOutResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "400":
          $ref: "#/components/responses/Error"

  /contacts/{external_user_id}/endpoints:
    get:
      tags: [Endpoints]
      summary: List endpoints for a Contact
      description: >
        Returns Endpoints for the Contact identified by `external_user_id`.
        Provider tokens (`address`) are omitted.
      operationId: listContactEndpoints
      parameters:
        - $ref: "#/components/parameters/ExternalUserId"
      responses:
        "200":
          description: Endpoint list
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/EndpointListResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
    post:
      tags: [Endpoints]
      summary: Register FCM endpoint
      operationId: registerEndpoint
      parameters:
        - $ref: "#/components/parameters/ExternalUserId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/EndpointCreate"
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                type: object
                properties:
                  endpoint_id: { type: string, format: uuid }
                  contact_id: { type: string, format: uuid }
                  channel: { type: string }
                  provider: { type: string }
                  platform: { type: string }
        "401":
          $ref: "#/components/responses/Unauthorized"

  /endpoints/{endpoint_id}:
    delete:
      tags: [Endpoints]
      summary: Deactivate endpoint
      operationId: deactivateEndpoint
      parameters:
        - name: endpoint_id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Deactivated
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          $ref: "#/components/responses/Error"
        "404":
          $ref: "#/components/responses/Error"

  /messages:
    get:
      tags: [Messages]
      summary: List Messages
      description: >
        Lists Project Messages. Omit `status` for Push history (excludes `draft`
        and archived Drafts). Pass `status=draft` for the Drafts list.
      operationId: listMessages
      parameters:
        - name: status
          in: query
          required: false
          schema:
            type: string
            enum: [draft, scheduled, preparing, processing, completed, failed, cancelled]
          description: >
            Filter by Message status. `draft` returns only non-archived Drafts.
            Other values never include drafts. Omit for Push history.
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
        - name: offset
          in: query
          schema: { type: integer, minimum: 0, default: 0 }
      responses:
        "200":
          description: Message list
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageList"
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Messages]
      summary: Create or schedule a message (Single send, Broadcast, or Draft)
      operationId: createMessage
      parameters:
        - name: Idempotency-Key
          in: header
          required: false
          schema: { type: string }
          description: >
            Project-scoped retry key. Same key + same body replays the stored 202
            response. Same key + different body returns 409 idempotency_conflict.
            Same key while the first request is incomplete returns 409
            idempotency_in_progress.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MessageCreate"
      responses:
        "202":
          description: >
            Accepted (new create or idempotent replay of a completed key).
            Replay returns the original MessageAccepted body. A Single send is built
            inside the request and returns `delivery_count` and `recipients`. A Broadcast
            returns status `preparing` without them: the worker builds its recipients in
            chunks, and `GET /messages/{id}` reports counts once it leaves `preparing`.
            A Broadcast whose Segment matches nobody ends as `failed` instead of
            returning 422 `no_active_endpoints`. A Draft (`draft: true`) returns
            status `draft` without delivery counts.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageAccepted"
              examples:
                singleSend:
                  value:
                    message_id: 0a1b2c3d-4e5f-6789-abcd-ef0123456789
                    channel: push
                    status: processing
                    delivery_count: 1
                    recipients: []
                broadcast:
                  value:
                    message_id: 1b2c3d4e-5f60-789a-bcde-f0123456789a
                    channel: push
                    status: preparing
                draft:
                  value:
                    message_id: 2c3d4e5f-6071-89ab-cdef-0123456789ab
                    channel: push
                    status: draft
        "400":
          $ref: "#/components/responses/ValidationError"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          $ref: "#/components/responses/IdempotencyConflict"
        "422":
          $ref: "#/components/responses/ValidationError"

  /messages/targeting/preview:
    post:
      tags: [Messages]
      summary: Preview Broadcast targeting
      description: >
        Evaluates a Broadcast targeting selector without creating a message.
        `platforms` is preview-only and filters endpoint counts; it is not a
        targeting selector and must not be sent under `targeting` on create.
      operationId: previewTargeting
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TargetingPreviewRequest"
            examples:
              builtinSegment:
                summary: Built-in subscribed Segment
                value:
                  segment_id: seg_sys_subscribed
                  platforms: [android, ios]
      responses:
        "200":
          description: Preview counts
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TargetingPreviewResponse"
              example:
                contacts: 120
                active_endpoints: 140
                android_endpoints: 90
                ios_endpoints: 50
        "400":
          $ref: "#/components/responses/ValidationError"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "422":
          $ref: "#/components/responses/ValidationError"

  /media:
    post:
      tags: [Media]
      summary: Upload a push image
      description: |
        Multipart upload of a JPEG or PNG (max 1MB). Field name must be `file`.
        Returns a project-scoped `asset_id` and a publicly reachable `url` suitable
        for `content.push.image_url`. Requires S3-compatible storage configuration.
        Dashboard session uploads use `/dashboard/projects/{projectId}/media` and
        are not part of this public specification.
      operationId: uploadMedia
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file:
                  type: string
                  format: binary
                  description: JPEG or PNG image, max 1MB
      responses:
        "201":
          description: Uploaded
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MediaUploadResponse"
              example:
                asset_id: 33333333-3333-4333-8333-333333333333
                url: https://cdn.example.com/organizations/.../images/33333333-3333-4333-8333-333333333333.png
        "400":
          $ref: "#/components/responses/ValidationError"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "413":
          description: File too large
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
              example:
                error:
                  code: file_too_large
                  message: Image must be at most 1MB
        "503":
          $ref: "#/components/responses/ServiceUnavailable"

  /messages/{id}:
    get:
      tags: [Messages]
      summary: Get message detail
      operationId: getMessage
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Notification detail including status summary (Deliveries are listed separately)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageDetail"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
    patch:
      tags: [Messages]
      summary: Update a Draft
      description: >
        Edits a Message in `draft` status. Requires the `updated_at` loaded from
        GET (optimistic concurrency); a stale value returns 409. Non-draft
        Messages return 409.
      operationId: updateDraft
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MessageDraftUpdate"
      responses:
        "200":
          description: Updated Draft
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageDetail"
        "400":
          $ref: "#/components/responses/ValidationError"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          $ref: "#/components/responses/Error"
    delete:
      tags: [Messages]
      summary: Archive a Draft
      description: >
        Archives a Draft (`deleted_at`). Non-draft Messages return 409.
        Archived Drafts are omitted from lists and GET returns 404.
      operationId: archiveDraft
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Archived
          content:
            application/json:
              schema:
                type: object
                properties:
                  message_id: { type: string, format: uuid }
                  status: { type: string, enum: [draft] }
                  archived: { type: boolean }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          $ref: "#/components/responses/Error"

  /messages/{id}/send:
    post:
      tags: [Messages]
      summary: Send a Draft
      description: >
        Runs full create validation on a Draft, then moves the same Message row
        to `scheduled` or `preparing`. The Message ID does not change.
      operationId: sendDraft
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "202":
          description: Draft accepted for send
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageAccepted"
        "400":
          $ref: "#/components/responses/ValidationError"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          $ref: "#/components/responses/Error"
        "422":
          $ref: "#/components/responses/ValidationError"

  /messages/{id}/deliveries:
    get:
      tags: [Messages]
      summary: List Deliveries for a Message
      description: |
        Cursor-paged Deliveries for one Message. Order is `created_at ASC, id ASC`.
        Pass `next_cursor` from a previous response as `cursor` to continue.
        Filter by Delivery `status` and Endpoint `platform` when set.
      operationId: listMessageDeliveries
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
        - name: cursor
          in: query
          required: false
          schema: { type: string }
          description: Opaque cursor from a previous `next_cursor`
        - name: status
          in: query
          required: false
          schema:
            $ref: "#/components/schemas/DeliveryStatus"
        - name: platform
          in: query
          required: false
          schema: { type: string, enum: [android, ios] }
      responses:
        "200":
          description: Page of Deliveries
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageDeliveryList"
        "400":
          $ref: "#/components/responses/ValidationError"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"

  /messages/{id}/cancel:
    post:
      tags: [Messages]
      summary: Cancel a Message while scheduled, preparing, or processing
      description: |
        Cancels a Message while it is `scheduled`, `preparing`, or `processing`.
        Deliveries not yet offered to the Provider become `skipped` with reason
        `cancelled`; Deliveries already sent stay sent. A finished Message
        (`completed`, `failed`, or already `cancelled`) returns 409.
      operationId: cancelMessage
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Cancelled
          content:
            application/json:
              schema:
                type: object
                properties:
                  message_id: { type: string, format: uuid }
                  status: { type: string, enum: [cancelled] }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          $ref: "#/components/responses/Error"

  /campaigns:
    post:
      tags: [Campaigns]
      summary: Create a Multi-send Campaign
      description: >
        Multi-send creates one Campaign and one child Message per recipient,
        each with its own Content. Recipients are addressed by External user ID.
        There is no RPC-style `/send` path.
      operationId: createCampaign
      parameters:
        - name: Idempotency-Key
          in: header
          required: false
          schema: { type: string }
          description: >
            Project-scoped retry key. Same key + same body replays the stored 202
            response. Same key + different body returns 409 idempotency_conflict.
            Same key while the first request is incomplete returns 409
            idempotency_in_progress.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CampaignCreate"
      responses:
        "202":
          description: >
            Accepted (new create or idempotent replay of a completed key).
            Replay returns the original CampaignAccepted body.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CampaignAccepted"
              examples:
                queued:
                  value:
                    campaign_id: 0a1b2c3d-4e5f-6789-abcd-ef0123456789
                    channel: push
                    status: queued
                    message_count: 2
                    messages:
                      - message_id: 11111111-1111-4111-8111-111111111111
                        external_user_id: user_a
                        status: processing
                        delivery_count: 1
                      - message_id: 22222222-2222-4222-8222-222222222222
                        external_user_id: user_b
                        status: processing
                        delivery_count: 1
        "400":
          $ref: "#/components/responses/ValidationError"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          $ref: "#/components/responses/IdempotencyConflict"
        "422":
          $ref: "#/components/responses/ValidationError"

  /campaigns/{id}:
    get:
      tags: [Campaigns]
      summary: Get Campaign and child Messages
      description: >
        Returns the Campaign, its child Messages, `message_counts` keyed by
        Message status (`scheduled`, `preparing`, `processing`, `completed`,
        `failed`, `cancelled`), and `delivery_totals` (nested Delivery rollups
        + CTR summed across child Messages; same nesting as Message
        `status_summary`).
      operationId: getCampaign
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Campaign detail including child Messages, Message counts, and Delivery totals
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CampaignDetail"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"

  /campaigns/{id}/cancel:
    post:
      tags: [Campaigns]
      summary: Cancel every cancellable Message under a Campaign
      description: |
        Cancels each child Message that is `scheduled`, `preparing`, or
        `processing` using the same rule as `cancelMessage`: Deliveries not yet
        offered to the Provider become `skipped` with reason `cancelled`;
        Deliveries already sent stay sent. Finished child Messages
        (`completed`, `failed`, or already `cancelled`) are left unchanged.
        Returns 409 when the Campaign has no cancellable Messages.
      operationId: cancelCampaign
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: At least one child Message was cancelled
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CampaignCancelled"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          $ref: "#/components/responses/Error"

  /segments:
    get:
      tags: [Segments]
      summary: List segments
      operationId: listSegments
      parameters:
        - $ref: "#/components/parameters/IncludeArchived"
      responses:
        "200":
          description: >
            Active segments by default. Pass `include_archived=true` to include
            archived segments.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SegmentListResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Segments]
      summary: Create segment
      description: >
        Creates a saved Segment. Rules must include at least one condition
        (use Everyone targeting for all Contacts). At most 50 conditions and
        1,000 values per `in` list. Name collisions return 409 `segment_name_taken`.
      operationId: createSegment
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SegmentCreate"
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SegmentMutationResponse"
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          description: >
            Name already used by an active Segment (`segment_name_taken`).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"

  /segments/counts:
    post:
      tags: [Segments]
      summary: Batch Segment contact and scheduled-message counts
      description: >
        Returns live `contact_count` and `scheduled_message_count` for a page of
        Segment IDs (saved UUIDs or builtin `seg_sys_*`). Dashboard list rows call
        this after the list loads. `contact_count` matches targeting preview with
        no platform or Category filter (Contacts with at least one offerable device).
      operationId: countSegments
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SegmentCountsRequest"
      responses:
        "200":
          description: Counts per Segment ID
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SegmentCountsResponse"
        "400":
          $ref: "#/components/responses/ValidationError"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "422":
          $ref: "#/components/responses/ValidationError"

  /segments/{id}:
    get:
      tags: [Segments]
      summary: Get segment
      operationId: getSegment
      parameters:
        - $ref: "#/components/parameters/SegmentId"
      responses:
        "200":
          description: Segment
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SegmentDetail"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
    put:
      tags: [Segments]
      summary: Update segment
      description: >
        Partial update: omitted fields keep their current values. Empty `name`
        is 400. Saving rules with zero conditions is 400 (use Everyone). At most
        50 conditions and 1,000 values per `in` list. Renaming onto an active
        Segment name returns 409 `segment_name_taken`.
      operationId: updateSegment
      parameters:
        - $ref: "#/components/parameters/SegmentId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SegmentUpdate"
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SegmentMutationResponse"
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          description: >
            Name already used by an active Segment (`segment_name_taken`).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
    delete:
      tags: [Segments]
      summary: Archive segment
      operationId: archiveSegment
      parameters:
        - $ref: "#/components/parameters/SegmentId"
      responses:
        "200":
          description: Archived
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SegmentMutationResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"

  /segments/{id}/restore:
    post:
      tags: [Segments]
      summary: Restore archived segment
      description: >
        Restores an archived Segment. If another active Segment already has the
        same name, returns 409 `segment_name_taken`.
      operationId: restoreSegment
      parameters:
        - $ref: "#/components/parameters/SegmentId"
      responses:
        "200":
          description: Restored
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SegmentMutationResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          description: >
            Name already used by an active Segment (`segment_name_taken`).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"

  /deliveries/{id}/delivered:
    post:
      tags: [Deliveries]
      summary: Mark delivery delivered (device acknowledgement)
      description: >
        Records that the device acknowledged receipt. Provider acceptance alone
        is status `sent`; this route advances the Delivery to `delivered`.
        Acks are accepted for 30 days after `sent_at` (or Delivery creation when
        unsent). Repeat acks return 200 with the stored status. SDKs drop 4xx
        responses from the ack queue.
      operationId: markDeliveryDelivered
      security: []
      parameters:
        - $ref: "#/components/parameters/DeliveryId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/DeliveryAck"
      responses:
        "200":
          description: >
            Acknowledged. Body `status` is the stored Delivery status (may already
            be `opened` when a delivered ack cannot downgrade).
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          description: Delivery is skipped or failed and cannot be acknowledged
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
        "410":
          description: >
            Acknowledgement window expired (30 days after send, or create when
            unsent), or the Project is deleted
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"

  /deliveries/{id}/opened:
    post:
      tags: [Deliveries]
      summary: Mark delivery opened
      description: >
        Records that the device opened the Notification (optionally with an
        action button). Acks are accepted for 30 days after `sent_at` (or Delivery
        creation when unsent). Repeat acks return 200 with the stored status.
        Unknown `action_id` values return 400. SDKs drop 4xx responses from the
        ack queue.
      operationId: markDeliveryOpened
      security: []
      parameters:
        - $ref: "#/components/parameters/DeliveryId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/DeliveryAck"
      responses:
        "200":
          description: Acknowledged. Body `status` is the stored Delivery status.
        "400":
          description: Invalid request or `action_id` not defined on this Notification
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          description: Delivery is skipped or failed and cannot be acknowledged
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
        "410":
          description: >
            Acknowledgement window expired (30 days after send, or create when
            unsent), or the Project is deleted
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"

  /mobile/notification-categories:
    get:
      tags: [Mobile]
      summary: List notification categories for the app
      operationId: mobileListCategories
      security:
        - mobileAppId: []
      parameters:
        - name: platform
          in: query
          required: false
          schema: { type: string, enum: [android], default: android }
          description: Only android is supported today
        - name: If-None-Match
          in: header
          required: false
          schema: { type: string }
          description: Return 304 when equal to the current ETag
      responses:
        "200":
          description: Categories for the platform
          headers:
            ETag:
              schema: { type: string }
              description: Opaque validator for conditional requests
            Cache-Control:
              schema: { type: string }
              description: private, max-age=0, must-revalidate
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MobileCategoriesResponse"
        "304":
          description: Not modified (If-None-Match matched ETag)
          headers:
            ETag:
              schema: { type: string }
            Cache-Control:
              schema: { type: string }
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/Error"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"

  /mobile/subscriptions:
    post:
      tags: [Mobile]
      summary: Register or refresh a device subscription (FCM token)
      description: |
        Registers a push token (201) or refreshes an owned active row (200).
        Present subscription_credential to update in place. Without ownership of an
        existing active token that already has a credential, ComRaid deactivates the
        previous endpoint (last-writer-wins) and issues a new subscription_id plus
        credential. A credential-less Endpoint (API / Dashboard / CSV import) holding
        the same token is taken over in place: same subscription_id and Contact, with a
        newly issued subscription_credential.
        subscription_credential is returned only when newly issued.
        Accepts Contact Properties (locale, timezone, language, country) and
        Subscription Properties (app_version, sdk_version, device.os/os_version/model).
        Create sets first_app_version and session_count=1; refresh updates current_*
        Properties and preserves first_app_version (does not increment session_count).
      operationId: mobileRegisterSubscription
      security:
        - mobileAppId: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MobileRegisterSubscriptionRequest"
            example:
              platform: android
              token: fcm-registration-token
              app_version: "1.2.0"
              device:
                model: Pixel 8
                os_version: "14"
      responses:
        "200":
          description: Existing owned token refreshed (same subscription_id)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MobileSubscriptionResponse"
        "201":
          description: New subscription created (anonymous until login); includes subscription_credential
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MobileSubscriptionResponse"
              example:
                subscription_id: 0a1b2c3d-4e5f-6789-abcd-ef0123456789
                subscription_credential: high-entropy-secret
                channel: push
                anonymous: true
                platform: android
                provider: fcm
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/Error"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"

  /mobile/subscriptions/{id}/login:
    post:
      tags: [Mobile]
      summary: Attach a contact identity to a subscription
      description: |
        Upserts a contact for external_user_id and binds this subscription.
        Requires a matching subscription_credential (credential-less Endpoints return 401).
        Inactive Subscriptions return 409 (`subscription_inactive`).
        When the project has identity_verification_required, jwt (RS256 JWT for Identity
        verification) is mandatory and must verify. When optional, omit jwt for an
        unverified bind, but any supplied invalid jwt is rejected (never downgraded).
      operationId: mobileSubscriptionLogin
      security:
        - mobileAppId: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MobileLoginRequest"
            example:
              external_user_id: user_123
              subscription_credential: high-entropy-secret
              jwt: eyJhbGciOiJSUzI1NiIsImtpZCI6ImFjbWUtMjAyNiJ9...
      responses:
        "200":
          description: Logged in
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MobileLoginResponse"
              example:
                subscription_id: 0a1b2c3d-4e5f-6789-abcd-ef0123456789
                contact_id: 9f8e7d6c-5b4a-3210-9876-543210fedcba
                external_user_id: user_123
                anonymous: false
                verified: true
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Error"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          description: Subscription is Inactive (`subscription_inactive`)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/Error"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"

  /mobile/subscriptions/{id}/token:
    post:
      tags: [Mobile]
      summary: Replace the push token on an existing subscription
      description: |
        Identity-preserving token rotation. Requires a matching subscription_credential
        (credential-less Endpoints return 401). Inactive Subscriptions return 409
        (`subscription_inactive`). Keeps subscription_id, contact association, verification,
        and delivery history. Another active holder of the new token is made Inactive.
        Also refreshes Subscription and Contact Properties when provided (does not increment session_count).
      operationId: mobileReplaceSubscriptionToken
      security:
        - mobileAppId: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MobileReplaceTokenRequest"
            example:
              token: new-fcm-or-apns-token
              platform: android
              provider: fcm
              subscription_credential: high-entropy-secret
      responses:
        "200":
          description: Token replaced (or refreshed when unchanged)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MobileReplaceTokenResponse"
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          description: Subscription is Inactive (`subscription_inactive`)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/Error"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"

  /mobile/subscriptions/{id}/session:
    post:
      tags: [Mobile]
      summary: Record an SDK session and refresh Properties
      description: |
        Increments Subscription `session_count`, advances `last_seen_at` / Contact
        `last_active_at`, and upserts first-class Properties (timezone, locale, language,
        country, app/OS versions). Distinct from customer Attributes.
        Requires a matching subscription_credential (credential-less Endpoints return 401).
        Inactive Subscriptions return 409 (`subscription_inactive`).
      operationId: mobileSubscriptionSession
      security:
        - mobileAppId: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MobileSessionRequest"
            example:
              subscription_credential: high-entropy-secret
              app_version: "2.0.0"
              locale: en-US
              timezone: America/New_York
              language: en
              country: US
              device:
                os: Android
                os_version: "14"
                model: Pixel 8
      responses:
        "200":
          description: Session recorded
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MobileSessionResponse"
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          description: Subscription is Inactive (`subscription_inactive`)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/Error"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"

  /mobile/subscriptions/{id}/logout:
    post:
      tags: [Mobile]
      summary: Make a subscription Inactive
      description: |
        Marks the Subscription Inactive (`is_active=false`) and clears its
        subscription credential so the old row cannot be reused. The SDK must
        immediately register a fresh Subscription on a new Anonymous contact.
        Requires a matching subscription_credential (credential-less Endpoints return 401).
      operationId: mobileSubscriptionLogout
      security:
        - mobileAppId: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                subscription_credential: { type: string }
      responses:
        "200":
          description: Logged out
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MobileLogoutResponse"
              example:
                subscription_id: 0a1b2c3d-4e5f-6789-abcd-ef0123456789
                active: false
                verified: false
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/Error"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"

  /mobile/subscriptions/{id}/opt-out:
    post:
      tags: [Mobile]
      summary: Opt the Contact out of a Channel
      description: |
        Records Opted out for the Subscription's Contact on the given Channel (push in V1).
        Requires a matching subscription_credential (credential-less Endpoints return 401).
        Inactive Subscriptions return 409 (`subscription_inactive`).
      operationId: mobileSubscriptionOptOut
      security:
        - mobileAppId: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MobileChannelOptOutRequest"
      responses:
        "200":
          description: Opted out
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MobileChannelOptOutResponse"
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          description: Subscription is Inactive (`subscription_inactive`)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
        "429":
          $ref: "#/components/responses/RateLimited"

  /mobile/subscriptions/{id}/opt-in:
    post:
      tags: [Mobile]
      summary: Clear Opted out for a Channel
      description: |
        Clears Opted out for the Subscription's Contact on the given Channel (push in V1).
        Requires a matching subscription_credential (credential-less Endpoints return 401).
        Inactive Subscriptions return 409 (`subscription_inactive`).
      operationId: mobileSubscriptionOptIn
      security:
        - mobileAppId: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MobileChannelOptOutRequest"
      responses:
        "200":
          description: Opted in
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MobileChannelOptOutResponse"
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          description: Subscription is Inactive (`subscription_inactive`)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
        "429":
          $ref: "#/components/responses/RateLimited"

  /mobile/subscriptions/{id}/attributes:
    put:
      tags: [Mobile]
      summary: Upsert Contact Attributes for a logged-in Subscription
      description: |
        Upserts Attributes on the Subscription's Contact. Requires App ID auth and a valid
        subscription credential (credential-less Endpoints return 401). Inactive Subscriptions
        return 409 (`subscription_inactive`). The Contact must be logged in (have an
        external_user_id); anonymous Subscriptions are rejected. JWT is not accepted on this
        call — use Login first. Same attribute upsert semantics as
        PUT /contacts/{external_user_id}/attributes, including JSON `null` to remove an Attribute.
      operationId: mobileSubscriptionUpsertAttributes
      security:
        - mobileAppId: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MobileAttributesUpsertRequest"
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactResponse"
        "400":
          $ref: "#/components/responses/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Error"
        "404":
          $ref: "#/components/responses/Error"
        "409":
          description: Subscription is Inactive (`subscription_inactive`)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorBody"
        "429":
          $ref: "#/components/responses/RateLimited"

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API key
      description: Project API key (cr_sk_...)
    mobileAppId:
      type: apiKey
      in: header
      name: X-ComRaid-App-Id
      description: Publishable mobile app id (cr_app_...)
  parameters:
    ExternalUserId:
      name: external_user_id
      in: path
      required: true
      schema: { type: string }
    SegmentId:
      name: id
      in: path
      required: true
      schema: { type: string, format: uuid }
    IncludeArchived:
      name: include_archived
      in: query
      required: false
      schema: { type: boolean, default: false }
      description: When true, include archived Segments in the list.
    DeliveryId:
      name: id
      in: path
      required: true
      schema: { type: string, format: uuid }
  responses:
    Unauthorized:
      description: Unauthorized
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorBody"
    Error:
      description: Error
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorBody"
    ValidationError:
      description: >
        Request was malformed or failed domain validation (typically 400 or 422).
        Codes include invalid_request, invalid_content, invalid_actions,
        invalid_category, targeting_invalid, invalid_image.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorBody"
          examples:
            targetingInvalid:
              value:
                error:
                  code: targeting_invalid
                  message: "Use only one targeting selector: segment_id, rules, or external_user_ids"
            invalidContent:
              value:
                error:
                  code: invalid_content
                  message: Channel push and content.push are required
    IdempotencyConflict:
      description: >
        Idempotency-Key conflict. `idempotency_conflict` means the same key was
        reused with a different body. `idempotency_in_progress` means the first
        request for this key has not finished storing its response yet.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorBody"
          examples:
            conflict:
              value:
                error:
                  code: idempotency_conflict
                  message: Same Idempotency-Key was used with a different request body
            inProgress:
              value:
                error:
                  code: idempotency_in_progress
                  message: Request with this Idempotency-Key is still in progress
    RateLimited:
      description: Too many requests
      headers:
        Retry-After:
          schema: { type: integer }
          description: Seconds until the client may retry
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorBody"
    ServiceUnavailable:
      description: Rate limiting or dependency temporarily unavailable
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorBody"
  schemas:
    ErrorBody:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message, request_id]
          properties:
            code:
              type: string
              description: >
                Stable machine-readable error code. Routing/framework codes include
                not_found (404), method_not_allowed (405), and internal_error (500).
            message:
              type: string
              description: Human-readable explanation
            request_id:
              type: string
              description: >
                Request correlation id; matches the X-Request-Id response header.
                Quote it when contacting support.
    MobileRegisterSubscriptionRequest:
      type: object
      required: [platform, token]
      properties:
        platform: { type: string, enum: [android, ios] }
        token: { type: string, description: FCM registration token or APNs device token }
        provider:
          type: string
          enum: [fcm, apns]
          description: >
            When omitted, android defaults to fcm and ios defaults to apns.
            Use provider=fcm with platform=ios for Firebase Messaging registration tokens.
            APNs is not valid for android.
        apns_environment:
          type: string
          enum: [sandbox, production]
          description: Required when provider is apns (or ios without an explicit fcm provider)
        app_version:
          type: string
          description: >
            Subscription Property current_app_version (and first_app_version on create).
            Also stored under metadata.app_version for legacy clients.
        sdk_version:
          type: string
          description: Subscription Property sdk_version
        locale:
          type: string
          description: Contact Property locale (BCP 47), e.g. en-US
        timezone:
          type: string
          description: Contact Property timezone (IANA), e.g. America/New_York
        language:
          type: string
          description: Contact Property language (ISO 639), e.g. en
        country:
          type: string
          description: Contact Property country (ISO 3166-1 alpha-2), e.g. US
        device:
          type: object
          additionalProperties: true
          description: >
            Device facts. Recognized keys os, os_version, model become Subscription
            Properties; the whole object is also stored under metadata.device.
          properties:
            os: { type: string }
            os_version: { type: string }
            model: { type: string }
        metadata:
          type: object
          additionalProperties: true
          description: Free-form metadata merged with device and app_version (not Properties)
        subscription_credential:
          type: string
          description: >
            Ownership secret issued at registration. Required to refresh the same
            subscription in place once issued. Omit on first register.
    MobileReplaceTokenRequest:
      type: object
      required: [token, platform, subscription_credential]
      properties:
        token: { type: string }
        platform: { type: string, enum: [android, ios] }
        provider:
          type: string
          enum: [fcm, apns]
        apns_environment:
          type: string
          enum: [sandbox, production]
        app_version: { type: string }
        sdk_version: { type: string }
        locale: { type: string }
        timezone: { type: string }
        language: { type: string }
        country: { type: string }
        device:
          type: object
          additionalProperties: true
          properties:
            os: { type: string }
            os_version: { type: string }
            model: { type: string }
        metadata:
          type: object
          additionalProperties: true
        subscription_credential:
          type: string
          description: Required ownership credential for this subscription
    MobileSessionRequest:
      type: object
      required: [subscription_credential]
      properties:
        subscription_credential: { type: string }
        app_version: { type: string }
        sdk_version: { type: string }
        locale: { type: string }
        timezone: { type: string }
        language: { type: string }
        country: { type: string }
        device:
          type: object
          additionalProperties: true
          properties:
            os: { type: string }
            os_version: { type: string }
            model: { type: string }
    MobileSessionResponse:
      type: object
      required: [subscription_id, session_count, last_seen_at]
      properties:
        subscription_id: { type: string, format: uuid }
        session_count: { type: integer, minimum: 1 }
        last_seen_at: { type: string, format: date-time }
    MobileReplaceTokenResponse:
      type: object
      required: [subscription_id, anonymous, platform, provider, verified, token_version]
      properties:
        subscription_id: { type: string, format: uuid }
        anonymous: { type: boolean }
        verified: { type: boolean }
        platform: { type: string, enum: [android, ios] }
        provider: { type: string, enum: [fcm, apns] }
        token_version: { type: integer }
    MobileSubscriptionResponse:
      type: object
      required: [subscription_id, channel, anonymous, platform]
      properties:
        subscription_id: { type: string, format: uuid }
        contact_id:
          type: string
          format: uuid
          description: Anonymous or known Contact bound to this Subscription
        channel: { type: string, enum: [push] }
        subscription_credential:
          type: string
          description: Returned only when newly issued; store securely on device
        anonymous:
          type: boolean
          description: True when the Contact has no external_user_id yet
        platform: { type: string, enum: [android, ios] }
        provider: { type: string, enum: [fcm, apns] }
    MobileLoginRequest:
      type: object
      required: [external_user_id]
      properties:
        external_user_id:
          type: string
          description: Product-owned contact identity
        subscription_credential:
          type: string
          description: Required once the subscription has been issued a credential
        jwt:
          type: string
          description: >
            RS256 JWT for Identity verification (iss=comraid:{project_id}, aud=comraid:identity,
            kid, iat, exp≤10m). Required when the project enforces identity verification.
    MobileLoginResponse:
      type: object
      required: [subscription_id, contact_id, external_user_id, anonymous, verified]
      properties:
        subscription_id: { type: string, format: uuid }
        contact_id: { type: string, format: uuid }
        external_user_id: { type: string }
        anonymous:
          type: boolean
          enum: [false]
        verified:
          type: boolean
          description: True when this login presented a valid Identity verification JWT
    MobileLogoutResponse:
      type: object
      required: [subscription_id, active, verified]
      properties:
        subscription_id: { type: string, format: uuid }
        active:
          type: boolean
          enum: [false]
          description: Always false; Logout makes the Subscription Inactive
        verified:
          type: boolean
          enum: [false]
    MobileChannelOptOutRequest:
      type: object
      required: [subscription_credential]
      properties:
        subscription_credential: { type: string }
        channel: { type: string, enum: [push], default: push }
    MobileAttributesUpsertRequest:
      type: object
      required: [subscription_credential, attributes]
      properties:
        subscription_credential: { type: string }
        attributes:
          type: object
          additionalProperties: true
          description: |
            Free-form Customer-supplied Attribute key/value pairs. Keys ≤ 128 chars;
            values ≤ 4KB serialized; ≤ 200 keys per Contact. JSON `null` removes that Attribute.
    MobileChannelOptOutResponse:
      type: object
      required: [subscription_id, contact_id, channel, opted_out]
      properties:
        subscription_id: { type: string, format: uuid }
        contact_id: { type: string, format: uuid }
        channel: { type: string, enum: [push] }
        opted_out: { type: boolean }
    MobileCategory:
      type: object
      required:
        - slug
        - name
        - android_channel_id
        - android_importance
        - android_lights
        - android_vibration
        - is_default
        - updated_at
      properties:
        slug: { type: string }
        name: { type: string }
        description: { type: string }
        android_channel_id: { type: string }
        android_importance: { type: string }
        android_sound: { type: string }
        android_lights: { type: boolean }
        android_vibration:
          description: Boolean or custom vibration pattern JSON as stored for the category
          oneOf:
            - type: boolean
            - type: array
              items: { type: number }
            - type: string
        is_default: { type: boolean }
        updated_at: { type: string, format: date-time }
    MobileCategoriesResponse:
      type: object
      required: [platform, categories]
      properties:
        platform: { type: string, enum: [android] }
        categories:
          type: array
          items:
            $ref: "#/components/schemas/MobileCategory"
    ContactCreate:
      type: object
      required: [external_user_id]
      properties:
        external_user_id: { type: string }
        name: { type: string }
        locale: { type: string, description: Contact Property locale }
        timezone: { type: string, description: Contact Property timezone (IANA) }
        language: { type: string, description: Contact Property language }
        country: { type: string, description: Contact Property country }
        metadata: { type: object, additionalProperties: true }
        attributes:
          type: object
          additionalProperties: true
          description: Customer-supplied Attributes (not SDK Properties); keys auto-register as project attribute definitions
    ContactUpsert:
      type: object
      properties:
        name: { type: string }
        locale: { type: string, description: Contact Property locale }
        timezone: { type: string, description: Contact Property timezone (IANA) }
        language: { type: string, description: Contact Property language }
        country: { type: string, description: Contact Property country }
        metadata: { type: object, additionalProperties: true }
        attributes:
          type: object
          additionalProperties: true
          description: Customer-supplied Attributes (not SDK Properties); omitted keys are left unchanged
    ContactResponse:
      type: object
      properties:
        contact_id: { type: string, format: uuid }
        external_user_id: { type: string }
        updated_attributes:
          type: array
          items: { type: string }
          description: Present when attributes were included in the request
    ContactPreference:
      type: object
      required: [category, channel, enabled]
      properties:
        category: { type: string }
        channel: { type: string, enum: [push] }
        enabled: { type: boolean }
        updated_at: { type: string, format: date-time }
    ContactPreferencesRequest:
      type: object
      required: [preferences]
      properties:
        preferences:
          type: array
          items:
            $ref: "#/components/schemas/ContactPreference"
    ContactPreferencesResponse:
      type: object
      properties:
        contact_id: { type: string, format: uuid }
        external_user_id: { type: string }
        preferences:
          type: array
          items:
            $ref: "#/components/schemas/ContactPreference"
    ContactOptOutRequest:
      type: object
      required: [opted_out]
      properties:
        opted_out: { type: boolean }
    ContactOptOutResponse:
      type: object
      required: [channel, opted_out]
      properties:
        contact_id: { type: string, format: uuid }
        external_user_id: { type: string }
        channel: { type: string, enum: [push] }
        opted_out: { type: boolean }
    ContactOptOutsResponse:
      type: object
      properties:
        contact_id: { type: string, format: uuid }
        external_user_id: { type: string }
        opt_outs:
          type: array
          items:
            type: object
            required: [channel, opted_out]
            properties:
              channel: { type: string, enum: [push] }
              opted_out: { type: boolean }
              updated_at: { type: string, format: date-time }
    EndpointCreate:
      type: object
      required: [address, platform]
      properties:
        channel: { type: string, enum: [push], default: push }
        provider:
          type: string
          enum: [fcm, apns]
          description: >
            When omitted, android defaults to fcm and ios defaults to apns.
            Use fcm with ios for Firebase Messaging tokens.
        address: { type: string, description: FCM registration token or APNs device token }
        platform: { type: string, enum: [android, ios] }
        metadata:
          type: object
          additionalProperties: true
          description: For APNs include apns_environment (sandbox or production)
    EndpointSummary:
      type: object
      required: [endpoint_id, channel, provider, is_active]
      properties:
        endpoint_id: { type: string, format: uuid }
        channel: { type: string }
        provider: { type: string }
        platform: { type: string, nullable: true }
        is_active: { type: boolean }
        created_at: { type: string, format: date-time }
        last_seen_at: { type: string, format: date-time, nullable: true }
    EndpointListResponse:
      type: object
      required: [endpoints]
      properties:
        endpoints:
          type: array
          items:
            $ref: "#/components/schemas/EndpointSummary"
    MessageCreate:
      type: object
      required: [channel, content]
      description: >
        Single send uses `to.external_user_ids`. Broadcast uses `targeting` with exactly
        one of `everyone`, `segment_id`, or `rules`. Do not put preview-only `platforms`
        on targeting — platform filters for sends live under `content.push.platforms`.
        Raw provider tokens are not a public targeting field. `to.endpoint_ids` is rejected.
        Set `draft: true` to save a Draft (title and body required; Segment optional;
        Broadcast Everyone or segment only; not Data-only).
      properties:
        draft:
          type: boolean
          default: false
          description: >
            When true, save as a Draft (`status: draft`) instead of sending.
            Segment may be empty. Limited to push Broadcast Everyone or segment_id.
        channel: { type: string, enum: [push], description: Required. Only push is accepted in V1. }
        to:
          type: object
          properties:
            external_user_ids:
              type: array
              items: { type: string }
              description: Single send recipients (External user IDs). Same Content for each.
        targeting:
          $ref: "#/components/schemas/TargetingSpec"
        category: { type: string }
        type: { type: string }
        name: { type: string }
        priority:
          type: string
          enum: [high, normal]
          description: Default `high`, or `normal` when `content.push.data_only` is true.
        ttl:
          type: integer
          minimum: 0
          maximum: 2419200
          description: >
            Time-to-live in seconds from send time (or from `send_at` when scheduled).
            Default 86400 (24 hours). Mapped to FCM Android TTL and APNs `apns-expiration`.
            `0` means send now and do not store (FCM `ttl: 0s`, APNs `apns-expiration: 0`);
            the worker offers once and does not retry. For TTL greater than 0, Deliveries
            past expiry are skipped as `ttl_expired`.
        collapse_key:
          type: string
          maxLength: 64
          description: >
            Collapse key so later sends with the same key replace earlier ones on device.
            Mapped to FCM `collapse_key` and APNs `apns-collapse-id`.
        data:
          type: object
          additionalProperties: true
          description: >
            Custom push data. Keys must not start with the reserved `cr_` prefix.
        send_at:
          type: string
          format: date-time
          nullable: true
          description: >
            Absolute UTC send time. Mutually exclusive with `send_at_local`.
        send_at_local:
          type: string
          nullable: true
          description: >
            Local wall-clock datetime without timezone (e.g. `2026-10-22T09:00:00`).
            Delivered when that clock time occurs in each recipient Contact's
            `timezone` Property. Contacts without a timezone (or with an invalid
            IANA name) fall back to UTC. Mutually exclusive with `send_at`.
          example: "2026-10-22T09:00:00"
        content:
          type: object
          required: [push]
          properties:
            push:
              type: object
              description: >
                Push Content. When `data_only` is false or omitted, `title` and `body`
                are required. When `data_only` is true, top-level Message `data` must be
                a non-empty object; `title`/`body` are optional app hints and actions
                remain allowed. The Provider does not present system tray UI for data-only.
              properties:
                data_only:
                  type: boolean
                  default: false
                  description: >
                    When true, deliver a Data-only Notification: no APNs alert and no
                    system tray UI from the Provider (optional title/body/actions are
                    app/SDK hints). Requires non-empty Message `data`. Android alerts
                    always omit the FCM `notification` block regardless (ADR 0014 —
                    the SDK presents `cr_*` data messages).
                title: { type: string }
                body: { type: string }
                image_url:
                  type: string
                  nullable: true
                  pattern: '^https?://'
                  description: >
                    Public http(s) URL for rich push images. Upload via POST /media
                    or supply an existing CDN URL.
                deep_link:
                  type: string
                  nullable: true
                  description: >
                    First-class deep link / launch URL delivered as `cr_deep_link` in
                    the push data payload for both Android and iOS.
                sound:
                  type: string
                  nullable: true
                  description: >
                    Custom notification sound resource name packaged in the app.
                    When omitted, APNs uses `default`.
                subtitle:
                  type: string
                  nullable: true
                  description: iOS alert subtitle (ignored on Android system notifications).
                badge:
                  type: integer
                  nullable: true
                  minimum: 0
                  description: >
                    iOS app icon badge. On Android, sent as `cr_badge` for the SDK-drawn
                    tray (notification count when the launcher supports it).
                thread_id:
                  type: string
                  nullable: true
                  description: >
                    iOS `thread-id` for notification grouping. On Android, mapped to
                    the notification tag.
                platforms:
                  type: array
                  items: { type: string, enum: [android, ios] }
                  description: Delivery platform filter for this send (not a targeting selector)
                actions:
                  type: array
                  maxItems: 3
                  description: Optional action buttons (max 3). Requires app display support.
                  items:
                    $ref: "#/components/schemas/PushAction"
    MessageDraftUpdate:
      type: object
      required: [updated_at, content]
      description: >
        Draft edit body. `updated_at` must match the value from GET (409 when stale).
        Same Draft shape rules as create with `draft: true`.
      properties:
        updated_at:
          type: string
          format: date-time
          description: Optimistic concurrency token from the loaded Draft.
        channel: { type: string, enum: [push] }
        targeting:
          $ref: "#/components/schemas/TargetingSpec"
        category: { type: string }
        type: { type: string }
        name: { type: string }
        priority:
          type: string
          enum: [high, normal]
        ttl:
          type: integer
          minimum: 0
          maximum: 2419200
        collapse_key:
          type: string
          maxLength: 64
        data:
          type: object
          additionalProperties: true
        send_at:
          type: string
          format: date-time
          nullable: true
        send_at_local:
          type: string
          nullable: true
        content:
          type: object
          required: [push]
          properties:
            push:
              type: object
              properties:
                title: { type: string }
                body: { type: string }
                image_url: { type: string, nullable: true, pattern: '^https?://' }
                deep_link: { type: string, nullable: true }
                sound: { type: string, nullable: true }
                subtitle: { type: string, nullable: true }
                badge: { type: integer, nullable: true, minimum: 0 }
                thread_id: { type: string, nullable: true }
                platforms:
                  type: array
                  items: { type: string, enum: [android, ios] }
                actions:
                  type: array
                  maxItems: 3
                  items:
                    $ref: "#/components/schemas/PushAction"
    MessageList:
      type: object
      properties:
        messages:
          type: array
          items:
            type: object
            additionalProperties: true
        total: { type: integer }
        limit: { type: integer }
        offset: { type: integer }
    MessageAccepted:
      type: object
      required: [message_id, channel, status]
      properties:
        message_id: { type: string, format: uuid }
        channel: { type: string }
        status:
          type: string
          enum: [draft, scheduled, preparing, processing, completed, failed, cancelled]
        delivery_count:
          type: integer
          description: Single send only. Absent for Broadcasts, which are built after the response.
        recipients:
          type: array
          description: Single send only. Absent for Broadcasts.
          items: { type: object, additionalProperties: true }
    CampaignCreate:
      type: object
      required: [channel, recipients]
      description: >
        Multi-send body. Each recipient is one Contact (by External user ID) with
        its own Content. The API creates one Campaign and one Message per recipient.
        Recipients are capped at 10,000 (same Contact cap as Single-send
        `to.external_user_ids`).
      properties:
        channel: { type: string, enum: [push], description: Required. Only push is accepted in V1. }
        name: { type: string, description: Optional Campaign label for inspection }
        recipients:
          type: array
          minItems: 1
          maxItems: 10000
          description: Per-Contact Contents. Maximum 10,000 recipients.
          items:
            type: object
            required: [external_user_id, content]
            properties:
              external_user_id: { type: string }
              category: { type: string }
              type: { type: string }
              name: { type: string }
              priority:
                type: string
                enum: [high, normal]
                description: Default `high`, or `normal` when `content.push.data_only` is true.
              ttl:
                type: integer
                minimum: 0
                maximum: 2419200
                description: >
                  Per-recipient TTL in seconds (default 86400). `0` means send now
                  and do not store (same as Message `ttl`).
              collapse_key:
                type: string
                maxLength: 64
              data:
                type: object
                additionalProperties: true
                description: >
                  Custom push data. Keys must not start with the reserved `cr_` prefix.
              content:
                type: object
                required: [push]
                properties:
                  push:
                    type: object
                    description: >
                      Per-recipient Push Content. Same `data_only` rules as Message create:
                      title/body required unless `data_only` is true (then recipient `data`
                      must be a non-empty object).
                    properties:
                      data_only:
                        type: boolean
                        default: false
                        description: >
                          When true, Data-only Notification for this recipient; no system
                          tray UI from the Provider. Requires non-empty recipient `data`.
                      title: { type: string }
                      body: { type: string }
                      image_url:
                        type: string
                        nullable: true
                        pattern: '^https?://'
                      deep_link: { type: string, nullable: true }
                      sound: { type: string, nullable: true }
                      subtitle: { type: string, nullable: true }
                      badge: { type: integer, nullable: true, minimum: 0 }
                      thread_id: { type: string, nullable: true }
                      platforms:
                        type: array
                        items: { type: string, enum: [android, ios] }
                      actions:
                        type: array
                        maxItems: 3
                        items:
                          $ref: "#/components/schemas/PushAction"
    CampaignAccepted:
      type: object
      required: [campaign_id, channel, status, messages]
      properties:
        campaign_id: { type: string, format: uuid }
        channel: { type: string }
        status:
          type: string
          enum: [queued, processing, completed, failed, cancelled]
        message_count: { type: integer }
        messages:
          type: array
          items:
            type: object
            required: [message_id, external_user_id, status]
            properties:
              message_id: { type: string, format: uuid }
              external_user_id: { type: string }
              status:
                type: string
                enum: [scheduled, preparing, processing, completed, failed, cancelled]
              delivery_count: { type: integer }
    CampaignDetail:
      type: object
      required: [campaign_id, channel, status, messages, message_counts, delivery_totals]
      properties:
        campaign_id: { type: string, format: uuid }
        channel: { type: string }
        status:
          type: string
          enum: [queued, processing, completed, failed, cancelled]
        name: { type: string }
        created_at: { type: string, format: date-time }
        message_count: { type: integer }
        message_counts:
          $ref: "#/components/schemas/CampaignMessageCounts"
        delivery_totals:
          $ref: "#/components/schemas/CampaignDeliveryTotals"
        messages:
          type: array
          items:
            type: object
            properties:
              message_id: { type: string, format: uuid }
              external_user_id: { type: string }
              status:
                type: string
                enum: [scheduled, preparing, processing, completed, failed, cancelled]
              title: { type: string }
              body: { type: string }
              delivery_count: { type: integer }
    CampaignDeliveryTotals:
      type: object
      description: >
        Nested Delivery rollups summed over every child Message of the Campaign.
        Same nesting as Message `status_summary`: delivered ⊆ sent, opened ⊆ delivered;
        `ctr` is opened ÷ delivered (0 when delivered is 0).
      required: [sent, delivered, opened, failed, skipped, total, ctr]
      properties:
        queued: { type: integer }
        processing: { type: integer }
        sent: { type: integer }
        failed: { type: integer }
        skipped: { type: integer }
        remaining: { type: integer }
        delivered: { type: integer }
        opened: { type: integer }
        total: { type: integer }
        ctr: { type: number, format: double }
    CampaignMessageCounts:
      type: object
      description: >
        Counts of child Messages under a Campaign, keyed by Message status.
        Every status key is always present (zero when none).
      required: [scheduled, preparing, processing, completed, failed, cancelled]
      properties:
        scheduled: { type: integer }
        preparing: { type: integer }
        processing: { type: integer }
        completed: { type: integer }
        failed: { type: integer }
        cancelled: { type: integer }
    CampaignCancelled:
      type: object
      required: [campaign_id, cancelled_count]
      properties:
        campaign_id: { type: string, format: uuid }
        cancelled_count:
          type: integer
          description: Number of child Messages cancelled by this request
    DeliveryStatus:
      type: string
      description: >
        Customer-facing Delivery outcome. `sent` means the Provider accepted the
        handoff; `delivered` means the device acknowledged receipt; `opened` is
        open/action ACK. `failed` is tried and could not complete; `skipped` was
        never offered to the Provider (cancel, Inactive, Opted out, preference
        block, invalid token, contact mismatch, and equivalents).
      enum: [queued, processing, sent, delivered, opened, failed, skipped]
    MessagePlatformStatusSummary:
      type: object
      description: >
        Nested Delivery rollups for one Endpoint platform (`android` or `ios`).
        Same nesting and CTR rules as the Message totals; android and ios counts
        sum to the top-level totals when every Delivery Endpoint is android or ios.
      properties:
        queued: { type: integer }
        processing: { type: integer }
        sent:
          type: integer
          description: >
            Deliveries the Provider accepted on this platform. Nested: includes
            later delivered and opened outcomes.
        delivered:
          type: integer
          description: >
            Deliveries with a delivered or opened timestamp on this platform.
            Nested under sent.
        opened:
          type: integer
          description: >
            Deliveries with open/action acknowledgement on this platform.
            Nested under delivered.
        failed: { type: integer }
        skipped: { type: integer }
        remaining: { type: integer }
        total:
          type: integer
          description: Delivery row count for this platform.
        ctr:
          type: number
          format: double
          description: >
            Opened ÷ delivered for this platform. Zero when delivered is zero.
    MessageStatusSummary:
      type: object
      description: >
        Per-Message Delivery rollups. Counts nest: `sent` is every Delivery the
        Provider accepted (`sent_at` set, or status sent/delivered/opened),
        including ones later delivered or opened; `delivered` is part of `sent`
        and `opened` is part of `delivered`. `failed` and `skipped` are separate
        end states; `queued` and `processing` are in-flight. `total` is the
        Delivery row count. `delivered` uses `received_at` (API `delivered_at`)
        or `opened_at`, so an open without a prior delivered ACK still counts as
        reached. `ctr` is opened ÷ delivered (0 when delivered is 0) and never
        exceeds 100%. `android` and `ios` repeat the same nested counts split by
        the Delivery's Endpoint platform (one grouped query). `failure_reasons`
        counts failed Deliveries by `error_code` (unknown when missing).
        Time-series charts and per-attempt history are out of V1 for this summary.
      properties:
        status: { type: string }
        humanized_status: { type: string }
        queued: { type: integer }
        processing: { type: integer }
        sent:
          type: integer
          description: >
            Deliveries the Provider accepted (`sent_at` set or status in
            sent/delivered/opened). Nested: includes later delivered and opened
            outcomes. Not device receipt alone — do not infer delivered from sent.
        delivered:
          type: integer
          description: >
            Deliveries with a delivered timestamp or an opened timestamp
            (opened-without-delivered still counts, so CTR cannot exceed 100%).
            Nested under sent.
        opened:
          type: integer
          description: >
            Deliveries with open/action acknowledgement. Nested under delivered.
        failed: { type: integer }
        skipped: { type: integer }
        remaining: { type: integer }
        total:
          type: integer
          description: >
            Delivery row count for the Message. With nesting,
            queued + processing + failed + skipped + sent equals total.
        ctr:
          type: number
          format: double
          description: >
            Click-through / open rate as opened ÷ delivered. Zero when delivered
            is zero. Never uses sent in the denominator.
        android:
          $ref: "#/components/schemas/MessagePlatformStatusSummary"
        ios:
          $ref: "#/components/schemas/MessagePlatformStatusSummary"
        failure_reasons:
          type: object
          additionalProperties: { type: integer }
          description: Counts of failed Deliveries keyed by error_code (unknown when blank)
        action_clicks: { type: object, additionalProperties: { type: integer } }
    DeliveryInspection:
      type: object
      properties:
        delivery_id: { type: string, format: uuid }
        channel: { type: string }
        provider: { type: string }
        platform: { type: string, nullable: true }
        model: { type: string, nullable: true }
        contact_id: { type: string, format: uuid, nullable: true }
        external_user_id:
          type: string
          nullable: true
          description: >
            Contact External user ID when known; null for an Anonymous contact.
        status: { $ref: "#/components/schemas/DeliveryStatus" }
        attempt_count: { type: integer }
        provider_message_id: { type: string, nullable: true }
        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 }
        opened_at: { type: string, format: date-time, nullable: true }
        failed_at: { type: string, format: date-time, nullable: true }
        error_code:
          type: string
          nullable: true
          description: >
            Stable skip/fail code (for example opted_out, invalid_token, ttl_expired,
            identity_unverified, cancelled, provider_error). Null after a successful send.
        error_message: { type: string, nullable: true }
        action_id: { type: string, nullable: true }
        action_clicked_at: { type: string, format: date-time, nullable: true }
    MessageDeliveryList:
      type: object
      required: [deliveries]
      properties:
        deliveries:
          type: array
          items: { $ref: "#/components/schemas/DeliveryInspection" }
        next_cursor:
          type: string
          description: Present when another page is available; pass as `cursor` on the next request
    MessageDetail:
      type: object
      properties:
        message_id: { type: string, format: uuid }
        campaign_id:
          type: string
          format: uuid
          nullable: true
          description: >
            Present when this Message was created by a Multi-send Campaign; null for
            Single send and Broadcast.
        status:
          type: string
          enum: [draft, scheduled, preparing, processing, completed, failed, cancelled]
        status_summary: { $ref: "#/components/schemas/MessageStatusSummary" }
        recipient: { type: object, additionalProperties: true, nullable: true }
        channel: { type: string }
        message: { type: object, additionalProperties: true }
        targeting: { type: object, additionalProperties: true, nullable: true }
        timing: { type: object, additionalProperties: true }
        attribution: { type: object, additionalProperties: true }
    BuiltinSegmentId:
      type: string
      description: >
        Built-in system segment identifiers. Prefixed with `seg_sys_`. Cannot be
        updated or archived via segment CRUD; valid as `targeting.segment_id`.
        Glossary names: Everyone (`seg_sys_subscribed`), New contacts
        (`seg_sys_new`), Recently active, Engaged, Dormant (`seg_sys_dormant` —
        Active Endpoints not seen recently, never called Inactive), Android/iOS
        contacts (also limit Message devices to that platform).
      enum:
        - seg_sys_subscribed
        - seg_sys_new
        - seg_sys_active
        - seg_sys_engaged
        - seg_sys_dormant
        - seg_sys_android
        - seg_sys_ios
    TargetingSpec:
      type: object
      description: |
        Broadcast targeting selector for message create. Exactly one of `everyone`,
        `segment_id`, or `rules` is required. External user ID lists belong on
        `to.external_user_ids` (Single send), not here. Does not include preview-only
        fields such as `platforms`.

        `everyone` is the Everyone selector (Contacts with at least one Active Endpoint
        on the Message's Channel who are not Opted out). Built-in Segments use string
        IDs (`seg_sys_*`); saved Segments use UUIDs. Glossary names for builtins:
        Everyone, New contacts, Recently active, Engaged, Dormant, Android contacts,
        iOS contacts.
      properties:
        everyone:
          type: boolean
          description: >
            Everyone — Contacts with at least one Active Endpoint on the Message's
            Channel who are not Opted out
        segment_id:
          oneOf:
            - $ref: "#/components/schemas/BuiltinSegmentId"
            - type: string
              format: uuid
          description: >
            Saved Segment UUID or built-in `seg_sys_*` (Everyone, New contacts,
            Recently active, Engaged, Dormant, Android contacts, iOS contacts)
        rules:
          $ref: "#/components/schemas/SegmentRules"
    TargetingPreviewRequest:
      allOf:
        - $ref: "#/components/schemas/TargetingSpec"
        - type: object
          properties:
            platforms:
              type: array
              items: { type: string, enum: [android, ios] }
              description: >
                Preview-only filter for endpoint platform counts. Not accepted on
                message create targeting; use content.push.platforms instead.
            category:
              type: string
              description: >
                Optional Notification Category slug. When set, preview counts exclude
                Contacts with that Category preference disabled (same offerability
                filter as Broadcast create). Omitted → Active + not Opted out only.
    TargetingPreviewResponse:
      type: object
      required: [contacts, active_endpoints, android_endpoints, ios_endpoints]
      properties:
        contacts:
          type: integer
          description: >
            Contacts with at least one device that can receive after platforms,
            Identity verification and Category (same gate as Broadcast Deliveries).
        active_endpoints: { type: integer }
        android_endpoints: { type: integer }
        ios_endpoints: { type: integer }
    SegmentRules:
      type: object
      required: [operator, conditions]
      properties:
        operator: { type: string, enum: [and, or] }
        conditions:
          type: array
          items:
            type: object
            required: [field, op]
            properties:
              field: { type: string }
              key: { type: string }
              op:
                type: string
                description: |
                  Condition operator. `neq X` matches exactly the Contacts that do not
                  match `eq X` (for `endpoint.*`, no Active device has X — Contacts with
                  no device or a null value match). App versions
                  (`endpoint.current_app_version`, `endpoint.first_app_version`) support
                  `eq` / `in` only.
                  For `contact_attribute`: `eq`, `neq`, `in`, `exists`, `not_exists`, and
                  typed comparisons `gt`, `gte`, `lt`, `lte` (numbers and dates only).
                  Contact Properties: `contact.locale`, `contact.timezone`,
                  `contact.language`, `contact.country` (string ops); `contact.last_active`,
                  `contact.first_seen` (RFC3339 comparisons, plus `within` / `not_within`
                  with a positive integer day count for relative windows).
                  Endpoint Properties: `endpoint.platform` (`eq`/`in`); `endpoint.is_active`
                  (`eq`); `endpoint.os`, `endpoint.os_version`, `endpoint.model`,
                  `endpoint.sdk_version` (string ops); `endpoint.session_count` (numeric);
                  `endpoint.last_seen`, `endpoint.first_seen` (RFC3339, plus `within` /
                  `not_within`). `endpoint.*` rules only pick Contacts; Android/iOS
                  builtin Segments also limit Message devices to that platform.
                  Communication preferences: `communication_preference` with category `key`.
                  Builtin `seg_sys_dormant` is the not-recently-seen Dormant Segment (never
                  called Inactive; Inactive is Endpoint-only).
              value: {}
    MediaUploadResponse:
      type: object
      required: [asset_id, url]
      properties:
        asset_id:
          type: string
          format: uuid
          description: Stable media asset id for this project
        url:
          type: string
          format: uri
          description: Public URL for content.push.image_url
    SegmentCreate:
      type: object
      required: [name, rules]
      description: >
        Create body. `rules.conditions` must be non-empty (at most 50). Each
        `in` list may have at most 1,000 values.
      properties:
        name: { type: string, minLength: 1 }
        description: { type: string }
        rules:
          $ref: "#/components/schemas/SegmentRules"
    SegmentUpdate:
      type: object
      description: >
        Partial update body. Omitted fields keep their current values. When
        `name` is sent it must be non-empty. When `rules` is sent it must have
        at least one condition (at most 50) and `in` lists at most 1,000 values.
      properties:
        name: { type: string, minLength: 1 }
        description: { type: string }
        rules:
          $ref: "#/components/schemas/SegmentRules"
    SegmentSummary:
      type: object
      required: [segment_id, name, status, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        segment_id: { type: string, format: uuid }
        name: { type: string }
        description: { type: string }
        rules:
          $ref: "#/components/schemas/SegmentRules"
        status: { type: string, enum: [active, archived] }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        archived_at:
          type: string
          format: date-time
          nullable: true
    SegmentDetail:
      type: object
      required: [segment_id, name, status, created_at, updated_at, contact_count, scheduled_message_count]
      properties:
        segment_id: { type: string, format: uuid }
        name: { type: string }
        description: { type: string, nullable: true }
        rules:
          $ref: "#/components/schemas/SegmentRules"
        status: { type: string, enum: [active, archived] }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        archived_at:
          type: string
          format: date-time
          nullable: true
        contact_count:
          type: integer
          description: >
            Live count of Contacts in this Segment with at least one offerable
            device (preview query with no platform or Category filter).
        scheduled_message_count:
          type: integer
          description: >
            Messages in `scheduled` or `preparing` whose targeting
            `source_segment_id` is this Segment.
    SegmentCountsRequest:
      type: object
      required: [segment_ids]
      properties:
        segment_ids:
          type: array
          minItems: 1
          maxItems: 100
          items:
            oneOf:
              - $ref: "#/components/schemas/BuiltinSegmentId"
              - type: string
                format: uuid
          description: Page of Segment IDs from the list (saved UUIDs or builtins)
    SegmentCountsResponse:
      type: object
      required: [counts]
      properties:
        counts:
          type: array
          items:
            type: object
            required: [segment_id, contact_count, scheduled_message_count]
            properties:
              segment_id: { type: string }
              contact_count: { type: integer }
              scheduled_message_count: { type: integer }
    SegmentListResponse:
      type: object
      required: [segments]
      properties:
        segments:
          type: array
          items:
            $ref: "#/components/schemas/SegmentSummary"
    SegmentMutationResponse:
      type: object
      required: [segment_id, status, updated_at]
      properties:
        segment_id: { type: string, format: uuid }
        status: { type: string, enum: [active, archived] }
        updated_at: { type: string, format: date-time }
    DeliveryAck:
      type: object
      required: [attribution_token]
      properties:
        attribution_token: { type: string }
        action_id:
          type: string
          description: Optional action button id on opened acknowledgements. Also marks the delivery opened.
    PushAction:
      type: object
      required: [id, text]
      properties:
        id: { type: string, description: Stable app-handled action identity }
        text: { type: string, description: Button label }
        icon: { type: string, description: Optional Android small-icon resource name }
