# OpenAPI 3.1 spec for the lockally control-plane API.
#
# This describes ONLY what's implemented today (Phase 3 skeleton).
# Endpoints planned in design §6.3 but not yet built (domains, mailboxes,
# send, webhooks, etc.) will be added as they ship.
#
# Lint with: redocly lint docs/openapi.yaml   (or any OpenAPI 3.1 linter)

openapi: 3.1.0

info:
  title: lockally control plane
  version: 0.1.0
  summary: REST API for managing tenants, domains, mailboxes, and outbound mail
  description: |
    The lockally control plane lets integrators and direct customers manage
    everything except actual mail data flow (which uses standard JMAP / IMAP /
    SMTP-submission against the data plane endpoints).

    **Authentication.** All `/v1/*` endpoints require a Bearer API key in the
    `Authorization` header. Keys are formatted `lk_live_<8-char-prefix>_<32-char-secret>`,
    or `lk_test_<...>` for a test key. Create keys in the dashboard, or with
    `POST /v1/api-keys` using a key that holds `tenant:admin`.

    The key's plan is checked on every request, so a key stops working if the
    account moves to a plan without API access, and works again if it moves back.

    **Errors.** Failures return [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457)
    `application/problem+json` documents.

    **Scopes.** Each endpoint requires a specific scope on the presented key.
    Insufficient scope returns `403` with the required scope name in `detail`.

  contact:
    name: lockally support
    email: support@lockally.com
  license:
    name: AGPL-3.0-only OR LicenseRef-LOC-Commercial
    identifier: AGPL-3.0-only

servers:
  - url: https://api.lockally.com
    description: Production
  - url: http://127.0.0.1:8081
    description: Local development / spike

security:
  - bearerAuth: []

tags:
  - name: health
    description: Liveness checks
  - name: agents
    description: "AI-native agent surface: inboxes, threads, drafts, grants (per-mailbox authorization)"
  - name: ai
    description: Metered LLM features (thread classification; BYOK or prepaid AI units)
  - name: test
    description: Test mode (lk_test_* keys)
  - name: tenant
    description: Operations on the calling tenant
  - name: api-keys
    description: API key lifecycle
  - name: domains
    description: Tenant-owned mail domains and DNS verification
  - name: mailboxes
    description: Mailboxes on verified tenant domains
  - name: aliases
    description: Email aliases (forwarders) on verified tenant domains
  - name: send
    description: Programmatic outbound mail (single, batch, scheduled, templated) + delivery stats
  - name: templates
    description: Reusable email templates with {{variable}} substitution
  - name: suppressions
    description: Suppression list, recipients Lockally won't mail (unsubscribes, complaints, hard bounces)
  - name: webhooks
    description: HMAC-signed event subscriptions
  - name: admin
    description: Tenant-admin login (email+password → session token for app.lockally.com)
  - name: admins
    description: Tenant-admin team management (invite, list, disable, delete)
  - name: users
    description: End-user (mailbox user) lifecycle
  - name: billing
    description: Plan, subscription checkout, and send-unit purchases
  - name: add-ons
    description: Paid add-on features (activation, cancellation)
  - name: distribution-lists
    description: Internal distribution / mailing lists
  - name: calendars
    description: "Calendars, events, members, policies, security, and integrations"
  - name: resources
    description: Bookable resources (meeting rooms, equipment)
  - name: contacts
    description: Contact records (internal and external)
  - name: contact-lists
    description: Contact list management and membership
  - name: directory
    description: "Global address list (GAL), directory permissions, stats"
  - name: encryption
    description: End-to-end encryption key management
  - name: ip-pools
    description: IP pool assignment and dedicated IP requests
  - name: dashboard
    description: "Tenant dashboard: user insights, audit, integrations, health, security, storage"
  - name: migrations
    description: Email migration from external providers (IMAP, Google, Microsoft)
  - name: signup
    description: Self-serve tenant registration (public, no auth)
  - name: drafts
    description: Agent draft review and approval (HITL)

paths:
  /healthz:
    get:
      operationId: healthCheck
      tags: [health]
      summary: Liveness check
      description: Returns 200 if the process is up and the database pings cleanly. No authentication required.
      security: []
      responses:
        '200':
          description: Healthy
          content:
            application/json:
              schema:
                type: object
                required: [status, time]
                properties:
                  status:
                    type: string
                    enum: [ok]
                  time:
                    type: string
                    format: date-time
        '503':
          $ref: '#/components/responses/ProblemServiceUnavailable'

  /v1/tenant:
    get:
      operationId: getTenant
      tags: [tenant]
      summary: Get the calling tenant
      description: Returns the tenant the presented API key belongs to.
      x-required-scope: tenant:read
      responses:
        '200':
          description: Tenant info
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Tenant' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/usage:
    get:
      operationId: getUsage
      tags: [tenant]
      summary: Usage snapshot
      description: |
        Returns the tenant's current usage + cap consumption. Designed for
        poll-based alerting on the integrator side (e.g. "warn when daily
        quota is 80% used"). Computed live on request, so there is no
        cache, so callers should poll at most once per minute.
      x-required-scope: tenant:read
      responses:
        '200':
          description: Usage snapshot
          content:
            application/json:
              schema:
                type: object
                required:
                  - mailboxes_active
                  - generated_at
                properties:
                  mailboxes_active:
                    type: integer
                    description: Mailboxes that are neither disabled nor soft-deleted.
                  mailboxes_total:
                    type: integer
                    description: All mailboxes for this tenant, including disabled/soft-deleted.
                  domains_verified:
                    type: integer
                    description: Domains that have passed DNS verification.
                  domains_total:
                    type: integer
                  messages_sent_last_60s:
                    type: integer
                    description: Sends in the 60-second window ending now. Used by the rate-cap check.
                  messages_sent_today_utc:
                    type: integer
                    description: Sends since 00:00 UTC. Compared against `daily_msg_quota`.
                  messages_sent_last_30d:
                    type: integer
                    description: Rolling 30-day send count (not calendar month).
                  bytes_stored:
                    type: integer
                    format: int64
                    description: Lifetime sum of `messages.size_bytes` for this tenant.
                  rate_cap_per_min:
                    type: integer
                    description: Per-tenant outbound rate cap (sends per minute).
                  daily_msg_quota:
                    type: integer
                    description: Per-tenant daily send quota (UTC day boundary).
                  webhooks_total:
                    type: integer
                  webhooks_paused:
                    type: integer
                    description: Webhook subscriptions auto-paused after 50 consecutive failures (LT2).
                  generated_at:
                    type: string
                    format: date-time
                    description: When this snapshot was generated, RFC 3339 UTC.
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/api-keys:
    get:
      operationId: listApiKeys
      tags: [api-keys]
      summary: List API keys
      description: |
        Returns all API keys (active and revoked) belonging to the calling
        tenant. The `secret` is **never** returned, only prefix + metadata.
      x-required-scope: tenant:admin
      parameters:
        - { name: sort, in: query, schema: { type: string, enum: [label, created_at, last_used_at, expires_at], default: created_at }, description: "Field to order by. This list holds tens of rows per account, so every column is offered and none needs an index." }
        - { name: order, in: query, schema: { type: string, enum: [asc, desc] }, description: "Defaults to desc for the default field and asc for any other. Always tie-broken on id, so the order is total." }
      responses:
        '200':
          description: Key list
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/APIKey' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

    post:
      operationId: createApiKey
      tags: [api-keys]
      summary: Create an API key
      description: |
        Provisions a fresh API key for the calling tenant.

        **The full `secret` is included in this response ONLY**, store it
        immediately. The cleartext secret is not recoverable from the
        argon2id hash kept server-side; rotate by creating a new key and
        revoking the old one.
      x-required-scope: tenant:admin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [label, scopes]
              properties:
                label:
                  type: string
                  description: Free-text identifier shown in the dashboard.
                  example: ci-pipeline
                scopes:
                  type: array
                  description: Allowed scopes on this key.
                  minItems: 1
                  items:
                    type: string
                    enum:
                      - tenant:read
                      - tenant:admin
                      - mailboxes:read
                      - mailboxes:write
                      - directory:sync
                      - inboxes:read
                      - inboxes:draft
                      - inboxes:write
                      - send:read
                      - send:write
                      - templates:read
                      - templates:write
                      - suppressions:read
                      - suppressions:write
                      - webhooks:read
                      - webhooks:write
                      - domains:read
                      - domains:write
                      - migrations:read
                      - migrations:write
                test:
                  type: boolean
                  default: false
                  description: |
                    Issue a test key (`lk_test_` prefix). A test key accepts sends,
                    records them and fires a simulated delivery webhook without
                    sending mail, and counts against no limit or allowance.
                expires_at:
                  type: string
                  format: date-time
                  description: |
                    Optional. When the key stops authenticating. Omit it for a
                    key that does not expire. Must be in the future: an expiry
                    already past would mint a key that fails its first request.
      responses:
        '201':
          description: Key created, `secret` is in the response and shown only here.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/APIKey'
                  - type: object
                    required: [secret]
                    properties:
                      secret:
                        type: string
                        description: The full `lk_live_<prefix>_<secret>` token. Shown ONCE.
                        example: lk_live_fbl73bhj_sfvqy7y757cnvu33bgqdpyrrhq3tyyf3
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/domains:
    get:
      operationId: listDomains
      tags: [domains]
      summary: List domains
      description: Returns every domain registered under the calling tenant.
      x-required-scope: domains:read
      parameters:
        - { name: sort, in: query, schema: { type: string, enum: [domain, created_at, verified_at], default: created_at }, description: "Field to order by. This list holds tens of rows per account, so every column is offered and none needs an index." }
        - { name: order, in: query, schema: { type: string, enum: [asc, desc] }, description: "Defaults to desc for the default field and asc for any other. Always tie-broken on id, so the order is total." }
      responses:
        '200':
          description: Domain list
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Domain' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

    post:
      operationId: createDomain
      tags: [domains]
      summary: Register a domain
      description: |
        Registers a new domain for the calling tenant. Generates a DKIM
        keypair and verification token. Returns DNS instructions the tenant
        must publish under their own DNS (verification TXT, SPF include,
        DKIM TXT, MX records to `mx1`/`mx2.lockally.com`, DMARC seed).

        **Idempotent**, re-posting the same domain returns the existing
        record with the same DKIM keys and token (regenerating would break
        the tenant's published DNS). Returns 200 on idempotent hit, 201 on
        first create.

        Returns 409 if the domain is already claimed by a different tenant.
      x-required-scope: domains:write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [domain]
              properties:
                domain:
                  type: string
                  format: hostname
                  example: acme.com
      responses:
        '200':
          description: Domain already registered to the calling tenant (idempotent).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Domain' }
        '201':
          description: Domain created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Domain' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '409':
          description: Domain claimed by another tenant.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/domains/{domain}:
    get:
      operationId: getDomain
      tags: [domains]
      summary: Get a domain
      x-required-scope: domains:read
      parameters:
        - { name: domain, in: path, required: true, schema: { type: string, format: hostname } }
      responses:
        '200':
          description: Domain record including the DNS instructions to publish.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Domain' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

    delete:
      operationId: deleteDomain
      tags: [domains]
      summary: Delete a domain
      description: |
        Removes the domain registration. Refuses with 409 if any mailbox is
        still attached, delete the mailboxes first.
      x-required-scope: domains:write
      parameters:
        - { name: domain, in: path, required: true, schema: { type: string, format: hostname } }
      responses:
        '204': { description: Deleted. }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Domain still has mailboxes attached.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/domains/{domain}/verify:
    post:
      operationId: verifyDomain
      tags: [domains]
      summary: Force-poll DNS verification
      description: |
        Synchronously checks the `_lockally-verify.<domain>` TXT record
        against the stored verification token. Returns 200 either way:
        the returned `verified` boolean tells you whether DNS now confirms.
        Caller polls until `verified: true`. A later version may have the platform
        auto-polls and fires a `domain.verified` webhook.
      x-required-scope: domains:write
      parameters:
        - { name: domain, in: path, required: true, schema: { type: string, format: hostname } }
      responses:
        '200':
          description: Current domain state (possibly newly verified).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Domain' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '502':
          description: Upstream DNS error (timeout, server unreachable). Retry.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/domains/{domain}/return-path:
    parameters:
      - { name: domain, in: path, required: true, schema: { type: string, format: hostname } }
    get:
      operationId: getReturnPath
      tags: [domains]
      summary: Get the custom Return-Path
      description: |
        A custom Return-Path moves the envelope sender of mail sent through the
        API from this domain onto `bounces.<domain>`. Bounce reports then come
        back to Lockally instead of the sending mailbox, and a bounce that
        arrives after delivery marks the message bounced, suppresses the
        address and fires `delivery.bounced`. Mail sent from webmail or mail
        apps is not affected. DKIM stays signed by the domain itself.
        `status` is `off`, `pending` (records not confirmed yet) or `active`.
      x-required-scope: domains:read
      responses:
        '200':
          description: Current state and the two DNS records to publish.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ReturnPath' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    post:
      operationId: enableReturnPath
      tags: [domains]
      summary: Turn on the custom Return-Path
      description: |
        Moves it to `pending` and returns the two records to publish on
        `bounces.<domain>`. Nothing changes for mail until they are confirmed
        with the verify call. The domain must be verified.
        Available on every plan except Free.
      x-required-scope: domains:write
      responses:
        '200':
          description: The Return-Path, now pending (or already active).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ReturnPath' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: The domain is not verified.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
    delete:
      operationId: disableReturnPath
      tags: [domains]
      summary: Turn off the custom Return-Path
      description: |
        API mail uses the sender's own address as the envelope sender again,
        from the next message.
      x-required-scope: domains:write
      responses:
        '204': { description: Turned off. }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/domains/{domain}/return-path/verify:
    post:
      operationId: verifyReturnPath
      tags: [domains]
      summary: Check the custom Return-Path records
      description: |
        Looks up the MX and SPF records on `bounces.<domain>`. Returns 200
        either way: while a record is missing the status stays `pending` and
        `check` says which one. Once both are found the Return-Path becomes
        `active` and the send path starts using it.
      x-required-scope: domains:write
      parameters:
        - { name: domain, in: path, required: true, schema: { type: string, format: hostname } }
      responses:
        '200':
          description: The Return-Path with the result of the check.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ReturnPath' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: The custom Return-Path is off. Turn it on first.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '502':
          description: The mail server could not be updated. Nothing changed; retry.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503':
          description: The records are correct but the feature is not available yet. Nothing changed.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/mailboxes:
    get:
      operationId: listMailboxes
      tags: [mailboxes]
      summary: List mailboxes
      description: |
        Returns mailboxes under the calling tenant, active and soft-deleted.
        `?limit=N` between 1 and 200 (default 50).
      x-required-scope: mailboxes:read
      parameters:
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
      responses:
        '200':
          description: Mailbox list.
          content:
            application/json:
              schema:
                type: object
                required: [data, limit]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Mailbox' }
                  limit: { type: integer }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

    post:
      operationId: createMailbox
      tags: [mailboxes]
      summary: Create a mailbox
      description: |
        Creates a mailbox on a tenant-verified domain. If `password` is
        omitted, lockally generates a 16-char password and returns it in the
        response, shown once.

        **Gate.** The mailbox's domain must already be registered AND
        verified for this tenant (via `/v1/domains` + `/v1/domains/{domain}/verify`).

        **Idempotent.** Re-posting the same email returns the existing
        mailbox UNTOUCHED, password is NOT regenerated. To change a
        password, use PATCH instead.
      x-required-scope: mailboxes:write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              properties:
                email:       { type: string, format: email, example: alice@acme.com }
                password:    { type: string, minLength: 8, description: "Optional; lockally generates if absent." }
                quota_bytes: { type: integer, format: int64, default: 5368709120, description: "5 GB default." }
      responses:
        '200':
          description: Mailbox already existed for this tenant (idempotent).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Mailbox' }
        '201':
          description: Mailbox created. `password` is in the response ONLY if generated.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Mailbox' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '409':
          description: Email claimed by another tenant.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/mailboxes/{email}:
    parameters:
      - { name: email, in: path, required: true, schema: { type: string, format: email } }
    get:
      operationId: getMailbox
      tags: [mailboxes]
      summary: Get a mailbox
      x-required-scope: mailboxes:read
      responses:
        '200':
          description: Mailbox info.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Mailbox' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

    patch:
      operationId: updateMailbox
      tags: [mailboxes]
      summary: Update a mailbox
      description: |
        Supply at least one of `password`, `quota_bytes`, `disabled`.
        Returns the updated mailbox.
      x-required-scope: mailboxes:write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                password:    { type: string, minLength: 8 }
                quota_bytes: { type: integer, format: int64, minimum: 0 }
                disabled:    { type: boolean }
      responses:
        '200':
          description: Updated mailbox.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Mailbox' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

    delete:
      operationId: deleteMailbox
      tags: [mailboxes]
      summary: Soft-delete a mailbox
      description: |
        Sets `soft_deleted_at = now()` and `hard_delete_after = now() + 90d`
        per design D25. A background sweep (planned) will hard-delete after
        the window. The mailbox is also disabled immediately.
      x-required-scope: mailboxes:write
      responses:
        '204': { description: Soft-deleted. }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/mailboxes/{email}/export:
    parameters:
      - { name: email, in: path, required: true, schema: { type: string } }
    post:
      operationId: exportMailbox
      tags: [mailboxes]
      summary: Request a mailbox export
      description: |
        Issues a one-shot "presigned" download URL for the mailbox's content
        in mbox format. The URL works without an Authorization header, the
        token in the query string is the authz. TTL is 5 minutes; the token
        is consumed on first GET.

        **v1 caveat:** the synthesized mbox only contains outbound mail
        (sent mail only). A later version will cover received mail
        for full inbox + folder structure + flags. The endpoint contract
        stays unchanged.

        **Scope changed:** this used to accept `mailboxes:read`. It takes any
        mailbox in the tenant and returns that mailbox's mail, so it now
        requires `tenant:admin`, matching `POST /v1/ediscovery/export`. A key
        scoped `mailboxes:read` gets 403 and has to be reissued; admin console
        sessions are unaffected.
      x-required-scope: tenant:admin
      responses:
        '201':
          description: Export token issued.
          content:
            application/json:
              schema:
                type: object
                required: [url, expires_at, format]
                properties:
                  url:
                    type: string
                    description: Relative download URL. Caller appends to the API host.
                  expires_at:
                    type: string
                    format: date-time
                  format:
                    type: string
                    enum: [mbox]
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/mailboxes/{email}/export/download:
    parameters:
      - { name: email, in: path, required: true, schema: { type: string } }
      - { name: token, in: query, required: true, schema: { type: string } }
    get:
      operationId: downloadMailboxExport
      tags: [mailboxes]
      summary: Download a previously-issued mailbox export
      description: |
        Public endpoint (no Authorization header). Validates the one-shot
        token from the URL, marks it used, and streams an mbox file. Second
        GET with the same token returns 404, tokens are single-use.
      security: []
      responses:
        '200':
          description: mbox stream.
          content:
            application/mbox:
              schema:
                type: string
                format: binary
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404':
          description: Token not found, already used, or expired.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/aliases:
    get:
      operationId: listAliases
      tags: [aliases]
      summary: List aliases
      x-required-scope: mailboxes:read
      responses:
        '200':
          description: Alias list.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Alias' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

    post:
      operationId: createAlias
      tags: [aliases]
      summary: Create an alias
      description: |
        Creates an email alias. `alias_address` must be on a verified
        tenant-owned domain and must not be the address of an existing mailbox
        (live, suspended or deleted). `alias_target` must be an active mailbox
        in the same workspace; forwarding to an address Lockally does not host
        is not supported. The alias delivers as soon as the call returns.
      x-required-scope: mailboxes:write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [alias_address, alias_target]
              properties:
                alias_address: { type: string, format: email, example: support@acme.com }
                alias_target:  { type: string, format: email, example: alice@acme.com }
      responses:
        '201':
          description: Alias created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Alias' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '409':
          description: Alias address already exists, or is a mailbox's own address.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/aliases/{address}:
    delete:
      operationId: deleteAlias
      tags: [aliases]
      summary: Delete an alias
      description: Hard-delete (no soft-delete window, aliases are cheap to recreate).
      x-required-scope: mailboxes:write
      parameters:
        - { name: address, in: path, required: true, schema: { type: string, format: email } }
      responses:
        '204': { description: Deleted. }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/admin/login:
    post:
      operationId: adminLogin
      tags: [admin]
      summary: Tenant-admin email+password login
      description: |
        Exchanges an admin's email + password for a session token. The web
        console at `app.lockally.com` posts this on form submission and
        stores the returned token in an httpOnly cookie.

        **No enumeration leak.** Wrong-email and wrong-password both return
        the same 401 with title "Invalid credentials". The argon2id verify
        runs even on lookup miss (well, structurally, the lookup fails fast
        but the response shape is constant) so timing leaks are bounded.

        Tokens are prefixed `adm_sess_` and valid for 7 days. Use as the
        `Authorization: Bearer` value on all subsequent calls.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, password]
              properties:
                email:    { type: string, format: email }
                password: { type: string, format: password, minLength: 8 }
      responses:
        '200':
          description: Authenticated.
          content:
            application/json:
              schema:
                type: object
                required: [token, expires_at, admin, tenant]
                properties:
                  token:      { type: string, example: "adm_sess_..." }
                  expires_at: { type: string, format: date-time }
                  admin:      { $ref: '#/components/schemas/Admin' }
                  tenant:     { $ref: '#/components/schemas/Tenant' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/admin/logout:
    post:
      operationId: adminLogout
      tags: [admin]
      summary: Invalidate the current admin session
      description: |
        Deletes the session row from the database. Idempotent, calling
        logout on an already-invalid token returns 204 anyway.
      responses:
        '204': { description: Logged out. }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }

  /v1/admin/me:
    get:
      operationId: getCurrentAdmin
      tags: [admin]
      summary: Get the current admin + tenant
      description: |
        Returns the admin profile + tenant for the session token presented
        in `Authorization: Bearer`. Used by the web console's layout load
        function to populate the sidebar.

        Returns 403 if called with an API key (lk_live_*) bearer, admin
        context only exists for session tokens.
      responses:
        '200':
          description: Admin + tenant.
          content:
            application/json:
              schema:
                type: object
                required: [admin, tenant]
                properties:
                  admin:  { $ref: '#/components/schemas/Admin' }
                  tenant: { $ref: '#/components/schemas/Tenant' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/admins:
    get:
      operationId: listAdmins
      tags: [admins]
      summary: List tenant admins
      x-required-scope: tenant:admin
      responses:
        '200':
          description: Admin list.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/AdminFull' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

    post:
      operationId: inviteAdmin
      tags: [admins]
      summary: Invite a new admin
      description: |
        Creates a new tenant admin. If `password` is omitted, lockally
        generates a 16-char password and returns it ONCE in the response.
        Email is case-insensitive and unique per tenant.
      x-required-scope: tenant:admin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              properties:
                email:        { type: string, format: email }
                password:     { type: string, format: password, minLength: 8 }
                display_name: { type: string }
                role:         { type: string, enum: [admin, viewer], default: admin }
      responses:
        '201':
          description: Created. `password` populated ONLY if generated.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AdminFull' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '409':
          description: Email already an admin on this tenant.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/admins/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
    patch:
      operationId: updateAdmin
      tags: [admins]
      summary: Update an admin
      description: |
        Supply at least one of `password`, `display_name`, `role`, `disabled`.

        **Safety rails.** A session bearer (adm_sess_*) cannot disable
        itself, use another admin or an API key (which bypasses the
        self-rail). Disabling the last active admin returns 409 to prevent
        orphaning the tenant from its console.
      x-required-scope: tenant:admin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                password:     { type: string, format: password, minLength: 8 }
                display_name: { type: string }
                role:         { type: string, enum: [admin, viewer] }
                disabled:     { type: boolean }
      responses:
        '200':
          description: Updated admin.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AdminFull' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Self-disable on session bearer, or last-admin safeguard.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

    delete:
      operationId: deleteAdmin
      tags: [admins]
      summary: Delete an admin
      description: |
        Hard-delete. Cascade-drops the admin's sessions (immediate
        revocation). Same safety rails as PATCH disabled=true.
      x-required-scope: tenant:admin
      responses:
        '204': { description: Deleted. }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Self-delete on session bearer, or last-admin safeguard.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/send:
    post:
      operationId: sendEmail
      tags: [send]
      summary: Send an email
      description: |
        Submits an email for delivery via lockally. Returns 202 immediately
        once the message is accepted into lockally's queue; the actual SMTP
        submission to the recipient is async. Track delivery via
        `GET /v1/messages/{id}` or webhook subscriptions for
        `delivery.delivered` / `delivery.bounced` / `delivery.complaint`.

        **Idempotency-Key required.** Any unique string per
        send, 24-hour dedupe window. Repeated calls with the same key
        return byte-exact the original response and do NOT create a
        duplicate message.

        **Sender authorisation.** `from` must be an address the calling
        tenant owns on a verified domain. A mailbox always qualifies. On
        business and combined accounts an **alias** qualifies too, so a
        send-only address such as `no-reply@` need not be a billed seat.
        An alias on an unverified domain, or one belonging to another
        account, is refused with `403`. A catch-all creates no aliases and
        so grants no sending rights.

        **Rate cap.** Per-tenant `rate_cap_per_min` (returned on
        `/v1/tenant`) is enforced, 429 with `Retry-After: 60` once tripped.

        **Recipient warning.** Over 25 total recipients (To+Cc+Bcc) sets a
        `warning` field in the response, large fan-outs queue noticeably
        at scale. Hard cap is 100/send.

        **Not every success is a 202.** Check the status code, not just the
        body. A `200` means nothing was queued: either every recipient was
        already suppressed, or the call used a test key and the send was
        simulated. Both are successes, and neither produces a real delivery.
        See the `200` response below.

        **Warm-up headers.** While the platform is in its outbound warm-up
        ramp, accepted sends carry `X-Warmup-Day`, `X-Warmup-Daily-Cap` and
        `X-Warmup-Used-Today`. They describe a platform-wide cap shared by
        every tenant, not your own allowance, and they disappear once the
        ramp finishes. Hitting the cap returns 429.
      x-required-scope: send:write
      parameters:
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 255 } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [from, to]
              properties:
                from:    { type: string, format: email }
                to:      { type: array, items: { type: string, format: email }, minItems: 1 }
                cc:      { type: array, items: { type: string, format: email } }
                bcc:     { type: array, items: { type: string, format: email } }
                subject: { type: string }
                text:    { type: string, description: "Plain-text body. Required if `html` is absent." }
                html:    { type: string, description: "HTML body. Required if `text` is absent." }
                headers: { type: object, additionalProperties: { type: string } }
                reply_to:      { type: string, format: email, description: "Where replies go. REQUIRED when `from` has no mailbox behind it, since a reply there would be delivered nowhere. A `Reply-To` entry in `headers` satisfies the same rule. The named form `Acme Support <a@b.com>` is also accepted." }
                reply_to_name: { type: string, description: "Display name shown on `Reply-To`, e.g. `Acme Support`. Ignored without `reply_to`. Encoded and quoted for you, so accents, commas and quotes are all safe." }
                unsubscribe: { type: boolean, description: "Mark as opt-in/broadcast: skips suppressed recipients and adds a managed one-click List-Unsubscribe header." }
                template_id: { type: string, format: uuid, description: "Render subject/text/html from a stored template (GET /v1/templates). Mutually exclusive with inline subject/text/html." }
                variables:   { type: object, additionalProperties: { type: string }, description: "Values substituted into the template's {{variable}} placeholders." }
                send_at:     { type: string, format: date-time, description: "Schedule delivery for a future RFC3339 time (≤ 30 days out). Omit or past = send now. Cancel with DELETE /v1/messages/{id} while scheduled." }
                metadata:
                  type: object
                  additionalProperties: { type: string }
                  maxProperties: 20
                  description: |
                    Arbitrary key/value you attach to this message and get back
                    on every delivery webhook for it, so a send can be matched
                    to your own records without a lookup table.

                    **It never leaves Lockally.** A custom entry in `headers`
                    goes out on the wire to the recipient, which is why that is
                    not a substitute: order ids and internal identifiers do not
                    belong in a header the recipient can read.

                    At most 20 keys, keys at most 64 characters, values at most
                    512. **Over a limit is refused with a `400`, never
                    truncated**: a silently shortened order id succeeds and then
                    fails to match weeks later.

                    Not indexed and not filterable.
                tags:
                  type: array
                  items: { type: string, maxLength: 32 }
                  maxItems: 10
                  description: |
                    Labels that group this send for filtering and analytics:
                    campaign, template, environment.

                    **Lowercased, trimmed and deduplicated on write**, so the
                    grouping does not depend on every caller spelling them
                    identically. `Campaign-X` is stored as `campaign-x`, and
                    either spelling matches it in a filter.

                    At most 10 per message after deduplication, each at most 32
                    characters. Over either is a `400` rather than a trimmed
                    list: a send missing the tag it was tagged for is worse than
                    a refusal.

                    Unlike `metadata`, tags ARE queryable: filter with
                    `GET /v1/messages?tag=` and group with
                    `GET /v1/messages/stats?tag=`.
                track_opens:
                  type: boolean
                  description: |
                    Override the account's open-tracking setting for this one
                    send. Omit to inherit it.

                    Three states matter here: `true`, `false`, and absent. A
                    transactional receipt can set `false` without the account
                    turning tracking off for its marketing.
                track_clicks:
                  type: boolean
                  description: |
                    As `track_opens`, for click tracking. Click tracking
                    rewrites `http(s)` links in the **HTML** part only: the
                    plain-text part is never rewritten, because a visible
                    redirect URL is what recipients complain about. A
                    text-only send is therefore not click-tracked.
                attachments:
                  type: array
                  items:
                    type: object
                    required: [filename, content_type, content_base64]
                    properties:
                      filename:       { type: string }
                      content_type:   { type: string, example: "application/pdf" }
                      content_base64: { type: string, description: "Base64-encoded body, max 10 MB decoded per attachment." }
      responses:
        '200':
          description: |
            Accepted, but nothing was queued for real delivery. Two cases, told
            apart by `status`:

            - `suppressed`, every recipient was on your suppression list, so
              the send was dropped. Deliberately a success, not a retryable
              error: retrying cannot change the outcome. There is no `id` or
              `message_id`, because no message was created. Complaint and
              bounce suppressions block every send; unsubscribe and manual
              suppressions block only opt-in sends (`unsubscribe: true`).
            - `delivered`, the call used a test key (`lk_test_`). The message
              is recorded and a `delivery.delivered` webhook fires with a
              simulated `250 OK`, but nothing leaves the platform. Test sends
              count against nothing: not your rate cap, allowance, send units,
              the warm-up ramp, or your reputation.
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  id:         { type: string, format: uuid, description: "Present on a test-mode send; absent when suppressed." }
                  message_id: { type: string, description: "RFC 5322 Message-ID. On a test send the domain is test.lockally.com. Absent when suppressed." }
                  status:     { type: string, enum: [suppressed, delivered] }
                  warning:    { type: string, description: "On a suppressed send, explains that nothing was sent." }
              examples:
                suppressed:
                  summary: Every recipient suppressed
                  value:
                    status: suppressed
                    warning: "All recipients are on your suppression list; nothing was sent."
                testMode:
                  summary: Simulated send on a test key
                  value:
                    id: "9f1c2b7a-3d4e-4f56-8a9b-0c1d2e3f4a5b"
                    message_id: "<9f1c2b7a-3d4e-4f56-8a9b-0c1d2e3f4a5b@test.lockally.com>"
                    status: delivered
        '202':
          description: Queued for delivery.
          headers:
            Idempotent-Replay:
              schema: { type: string }
              description: '"true" when the response is replayed from the idempotency cache.'
            X-Warmup-Day:
              schema: { type: integer }
              description: "Present only during the platform's outbound warm-up ramp: which day of the ramp this send landed on."
            X-Warmup-Daily-Cap:
              schema: { type: integer }
              description: "Warm-up ramp only: total messages the whole platform may send today, shared across all tenants."
            X-Warmup-Used-Today:
              schema: { type: integer }
              description: "Warm-up ramp only: how much of that platform-wide cap was already used when this send was accepted."
          content:
            application/json:
              schema:
                type: object
                required: [id, message_id, status]
                properties:
                  id:         { type: string, format: uuid, description: "Lockally identifier; use with GET /v1/messages/{id}." }
                  message_id: { type: string, description: "RFC 5322 Message-ID (with angle brackets)." }
                  status:     { type: string, enum: [queued, scheduled], description: "\"scheduled\" when send_at is in the future." }
                  warning:    { type: string }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '429':
          description: |
            Rate limited. Either your per-tenant `rate_cap_per_min`, or the
            platform-wide warm-up cap for the day (which resets at UTC
            midnight, so `Retry-After` can be hours rather than 60 seconds).
          headers:
            Retry-After:
              schema: { type: integer }
              description: "60 for the per-tenant cap; seconds until UTC midnight when the warm-up cap is what was hit."
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/send/batch:
    post:
      operationId: sendEmailBatch
      tags: [send]
      summary: Send a batch of emails
      description: |
        Sends up to 500 messages in one call. Each is validated and enqueued
        independently, a bad message fails only its own slot (partial success,
        HTTP 200). One `Idempotency-Key` header covers the batch; per-message
        keys are derived as `<key>:<index>`.
      x-required-scope: send:write
      parameters:
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 200 } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [messages]
              properties:
                messages:
                  type: array
                  minItems: 1
                  maxItems: 500
                  items: { $ref: '#/components/schemas/SendMessage' }
                variables:
                  type: object
                  additionalProperties: { type: string }
                  description: |
                    Template variables every message in the batch inherits.
                    Each message's own `variables` override these key by key,
                    so shared values are written once and per-recipient ones
                    stay per-recipient.

                    Without this, a 500-message batch repeats every shared
                    variable 500 times: most of the payload, and 500 places for
                    one of them to differ by a typo.
      responses:
        '200':
          description: Per-message results (partial success).
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/BatchResult' } }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/templates:
    get:
      operationId: listTemplates
      tags: [templates]
      summary: List templates
      x-required-scope: templates:read
      parameters:
        - { name: sort, in: query, schema: { type: string, enum: [name, created_at, updated_at], default: name }, description: "Field to order by. This list holds tens of rows per account, so every column is offered and none needs an index." }
        - { name: order, in: query, schema: { type: string, enum: [asc, desc] }, description: "Defaults to asc for the default field and asc for any other. Always tie-broken on id, so the order is total." }
      responses:
        '200':
          description: Templates.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/Template' } }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    post:
      operationId: createTemplate
      tags: [templates]
      summary: Create a template
      x-required-scope: templates:write
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TemplateInput' }
      responses:
        '201':
          description: Created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Template' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/templates/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
    get:
      operationId: getTemplate
      tags: [templates]
      summary: Get a template
      x-required-scope: templates:read
      responses:
        '200':
          description: Template.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Template' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    put:
      operationId: updateTemplate
      tags: [templates]
      summary: Update a template
      x-required-scope: templates:write
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TemplateInput' }
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Template' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    delete:
      operationId: deleteTemplate
      tags: [templates]
      summary: Delete a template
      x-required-scope: templates:write
      responses:
        '204': { description: Deleted. }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/suppressions:
    get:
      operationId: listSuppressions
      tags: [suppressions]
      summary: List suppressed recipients
      x-required-scope: suppressions:read
      parameters:
        - { name: reason, in: query, schema: { type: string, enum: [unsubscribe, complaint, bounce, manual] } }
        - { name: cursor, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, default: 50, maximum: 200 } }
      responses:
        '200':
          description: Suppressions.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/Suppression' } }
                  next_cursor: { type: string }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
    post:
      operationId: createSuppression
      tags: [suppressions]
      summary: Add a suppression
      x-required-scope: suppressions:write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              properties:
                email:  { type: string, format: email }
                reason: { type: string, enum: [unsubscribe, complaint, bounce, manual], default: manual }
      responses:
        '201':
          description: Added.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Suppression' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }

  /v1/suppressions/{email}:
    parameters:
      - { name: email, in: path, required: true, schema: { type: string, format: email } }
    get:
      operationId: getSuppression
      tags: [suppressions]
      summary: Check whether an address is suppressed
      x-required-scope: suppressions:read
      responses:
        '200':
          description: Suppressed.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Suppression' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    delete:
      operationId: deleteSuppression
      tags: [suppressions]
      summary: Remove a suppression
      x-required-scope: suppressions:write
      responses:
        '204': { description: Removed. }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/messages/stats:
    get:
      operationId: getMessageStats
      tags: [send]
      summary: Aggregate delivery stats
      description: |
        Counts by delivery outcome (delivered/bounced/deferred/complaint) plus
        rates over a window, from the delivery-event store. Privacy-first: this
        reflects what receiving servers reported, NOT whether a human opened the
        mail, Lockally does no open/click tracking.
      x-required-scope: send:read
      parameters:
        - { name: from, in: query, schema: { type: string, format: date-time }, description: "Window start (default 7 days ago)." }
        - { name: to, in: query, schema: { type: string, format: date-time }, description: "Window end (default now)." }
        - { name: domain, in: query, schema: { type: string }, description: "Filter by sender domain." }
        - { name: tag, in: query, schema: { type: string }, description: "Group the window by the sender's own tags: one tag, or a comma-separated set meaning ANY. Case-insensitive. This is the dimension that tells a transactional stream from a notification one." }
      responses:
        '200':
          description: Stats.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MessageStats' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }

  /v1/messages/{id}:
    get:
      operationId: getMessage
      tags: [send]
      summary: Get message status
      x-required-scope: send:read
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Message record with the content captured at send time.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MessageDetail' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    delete:
      operationId: cancelMessage
      tags: [send]
      summary: Cancel a scheduled send
      description: Cancels a still-scheduled message (future queued_at). Already sending/sent → 409.
      x-required-scope: send:write
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '204': { description: Cancelled. }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Not cancellable (already sending or sent).
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/webhooks:
    get:
      operationId: listWebhooks
      tags: [webhooks]
      summary: List webhooks
      description: |
        Returns the calling tenant's webhook subscriptions. Never returns
        the signing secret, only metadata.
      x-required-scope: webhooks:read
      responses:
        '200':
          description: Webhook list.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Webhook' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

    post:
      operationId: createWebhook
      tags: [webhooks]
      summary: Create a webhook
      description: |
        Subscribes a URL to one or more event types. Returns the
        `signing_secret` ONCE in the response, store it immediately.
        Every outbound POST is signed:

            X-Lockally-Signature: t=<unix>,v1=<hex(hmac_sha256(secret, t + "." + body))>

        Verify on your end using HMAC-SHA256 with a 5-minute timestamp
        window (replay protection). A reference verifier ships in
        [Signature verification](https://developers.lockally.com/webhooks/verification/).

        Event names: see the [event catalogue](https://developers.lockally.com/webhooks/events/).
      x-required-scope: webhooks:write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url, events]
              properties:
                url:
                  type: string
                  format: uri
                  description: HTTPS recommended (HTTP allowed for local development).
                  example: https://example.com/webhooks/lockally
                events:
                  type: array
                  minItems: 1
                  items: { type: string, example: domain.verified }
      responses:
        '201':
          description: Created. `signing_secret` is in the response ONLY here.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Webhook' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/webhooks/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
    patch:
      operationId: updateWebhook
      tags: [webhooks]
      summary: Update a webhook
      description: |
        Supply at least one of `url`, `events`, `paused`. Setting `paused`
        to `false` ALSO resets `consecutive_failures` to 0, re-arms the
        50-failure auto-pause counter.
      x-required-scope: webhooks:write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                url:    { type: string, format: uri }
                events: { type: array, items: { type: string } }
                paused: { type: boolean }
      responses:
        '200':
          description: Updated webhook.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Webhook' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

    delete:
      operationId: deleteWebhook
      tags: [webhooks]
      summary: Delete a webhook
      description: Hard-delete; cascades to `webhook_deliveries` history.
      x-required-scope: webhooks:write
      responses:
        '204': { description: Deleted. }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/api-keys/{id}:
    patch:
      operationId: updateApiKey
      tags: [api-keys]
      summary: Update an API key
      description: |
        Changes a key's label, scopes or expiry in place, without reissuing the
        secret.

        **Every field is optional and absent means unchanged.** Renaming a key
        does not clear its expiry. For `expires_at` there are three distinct
        requests: omit the field to leave the expiry alone, send a timestamp to
        set one, and send an explicit `null` to remove one.

        Scopes are replaced wholesale, not merged. This endpoint does not
        restrict which scopes you may grant, because `POST /v1/api-keys` never
        has either: a key with `tenant:admin` can already mint a key with any
        scope, so `tenant:admin` is root-equivalent for key management.

        A revoked key cannot be updated.
      x-required-scope: tenant:admin
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                label:
                  type: string
                  description: Free-text identifier shown in the dashboard.
                scopes:
                  type: array
                  minItems: 1
                  items: { type: string }
                  description: Replaces the key's scopes entirely.
                expires_at:
                  type: string
                  format: date-time
                  nullable: true
                  description: A future timestamp to set an expiry, or null to remove one.
      responses:
        '200':
          description: The updated key.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/APIKey' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: The key is revoked and cannot be changed.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

    delete:
      operationId: revokeApiKey
      tags: [api-keys]
      summary: Revoke an API key
      description: |
        Soft-deletes (sets `revoked_at`) on the named key. The row stays for
        audit purposes; the key no longer authenticates.

        You **cannot revoke the key currently being used** to make this
        call, that would lock you out. Use a different `tenant:admin` key.
      x-required-scope: tenant:admin
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '204':
          description: Revoked.
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Refused, key is the one in use for this request.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/messages:
    get:
      operationId: listMessages
      tags: [send]
      summary: List outbound messages
      description: |
        Returns recent outbound messages for the calling tenant, sorted
        newest first.
      x-required-scope: send:read
      parameters:
        - { name: status, in: query, schema: { type: string, enum: [queued, sending, delivered, bounced, deferred, complaint] } }
        - { name: sender, in: query, schema: { type: string }, description: "Exact match against the `from` mailbox." }
        - { name: tag, in: query, schema: { type: string }, description: "Filter to messages carrying any of these tags. One tag, or a comma-separated set meaning ANY. Case-insensitive: the value is normalised the same way tags are on write." }
        - { name: q, in: query, schema: { type: string }, description: "Free-text search across subject + sender." }
        - { name: since, in: query, schema: { type: string, format: date-time }, description: "Only messages queued at or after this RFC 3339 instant." }
        - { name: cursor, in: query, schema: { type: string }, description: "queued_at of the prior page boundary. Pass back the `next_cursor` returned by the previous call." }
        - { name: limit, in: query, schema: { type: integer, default: 50, maximum: 200 } }
        - { name: sort, in: query, schema: { type: string, enum: [queued_at, updated_at], default: queued_at }, description: "Field to order by. Only indexed columns are offered: an unindexed sort on this table is a full scan of the account's send history. status and sender are filters instead." }
        - { name: order, in: query, schema: { type: string, enum: [asc, desc] }, description: "Defaults to desc for the default field and asc for any other. The order is always made total by a tie-break on id, so paging cannot repeat or skip a row that shares a timestamp. cursor encodes queued_at, so combining it with another sort is a 400 rather than a wrong page." }
      responses:
        '200':
          description: List of messages + optional next-page cursor.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Message' }
                  next_cursor:
                    type: string
                    description: Pass as `cursor` to fetch the next page. Absent on the final page.
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  # ══════════════ Agent API (AI-native) ══════════════
  # inboxes:read / inboxes:write scopes are NOT tenant-wide: an API key may
  # only touch mailboxes it has an explicit grant for (see
  # /v1/api-keys/{keyID}/mailboxes). Every call is written to the tenant's
  # append-only agent audit log. Reads never mark mail as seen.

  /v1/auth/whoami:
    get:
      operationId: whoami
      tags: [agents]
      summary: Introspect the calling credentials
      description: Returns the tenant, auth kind (api_key/session), key label, and granted scopes. The MCP server uses this to scope-filter tool discovery.
      responses:
        "200": { description: "Caller identity", content: { application/json: { schema: { $ref: '#/components/schemas/Whoami' } } } }

  /v1/inboxes:
    get:
      operationId: listInboxes
      tags: [agents]
      summary: List granted inboxes
      description: The mailboxes this key is granted, with thread counts and last activity. Admin sessions see every agent-enabled, non-E2E mailbox.
      x-required-scope: inboxes:read
      responses:
        "200": { description: "Granted inboxes", content: { application/json: { schema: { $ref: '#/components/schemas/InboxList' } } } }

  /v1/contacts/lookup:
    get:
      operationId: lookupContact
      tags: [agents]
      summary: Who is this sender?
      description: "Directory record (name, company, role, notes), whether the address is one of the tenant's own mailboxes, and grant-aware correspondence history (thread count, first/last seen across granted mailboxes only)."
      x-required-scope: inboxes:read
      parameters:
        - { name: email, in: query, required: true, schema: { type: string, format: email } }
      responses:
        "200": { description: "Enrichment result", content: { application/json: { schema: { $ref: '#/components/schemas/ContactLookup' } } } }

  /v1/inboxes/{mailbox}/threads:
    get:
      operationId: listThreads
      tags: [agents]
      summary: List conversation threads
      description: "Newest-active first. Cursors: `?before=<RFC3339>` pages backwards; `?since=<RFC3339>` delta-syncs forward (oldest first) so an agent can catch up in order."
      x-required-scope: inboxes:read
      parameters:
        - { name: mailbox, in: path, required: true, schema: { type: string }, description: mailbox email or id }
        - { name: since,  in: query, schema: { type: string, format: date-time } }
        - { name: before, in: query, schema: { type: string, format: date-time } }
        - { name: limit,  in: query, schema: { type: integer, default: 50, maximum: 200 } }
      responses:
        "200": { description: "Threads", content: { application/json: { schema: { $ref: '#/components/schemas/ThreadList' } } } }

  /v1/inboxes/{mailbox}/messages:
    post:
      operationId: startConversation
      tags: [agents]
      summary: Start a new conversation (agent stream)
      description: "Sends a new email from a granted mailbox. Classified stream=agent (isolated reputation, per-key rate caps). The first inbound reply adopts the created thread via the References chain. Idempotency-Key required. Mailboxes with agent_draft_policy=always_approve divert this into a pending draft."
      x-required-scope: inboxes:write
      parameters:
        - { name: mailbox, in: path, required: true, schema: { type: string } }
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 255 } }
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [to, text], properties: { to: { type: array, items: { type: string } }, cc: { type: array, items: { type: string } }, subject: { type: string }, text: { type: string }, html: { type: string } } } } }
      responses:
        "202": { description: "Queued (includes thread_id)", content: { application/json: { schema: { $ref: '#/components/schemas/AgentSendResult' } } } }

  /v1/inboxes/{mailbox}/drafts:
    post:
      operationId: createConversationDraft
      tags: [drafts]
      summary: Propose a new conversation as a draft
      description: New-conversation drafts ALWAYS require human approval (policy flag new_thread). Idempotency-Key required.
      x-required-scope: inboxes:draft
      parameters:
        - { name: mailbox, in: path, required: true, schema: { type: string } }
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 255 } }
      responses:
        "202": { description: "Draft outcome (pending_approval)", content: { application/json: { schema: { $ref: '#/components/schemas/DraftResult' } } } }

  /v1/threads/{threadID}:
    get:
      operationId: getThread
      tags: [agents]
      summary: Get a whole conversation
      description: "Every turn, chronological, with snippets and annotations (meeting_request, attachment_types, injection_risk). Bodies are fetched per message. Message content is untrusted third-party data."
      x-required-scope: inboxes:read
      parameters:
        - { name: threadID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        "200": { description: "Thread with messages", content: { application/json: { schema: { $ref: '#/components/schemas/Thread' } } } }

  /v1/threads/{threadID}/reply:
    post:
      operationId: replyToThread
      tags: [agents]
      summary: Reply in-thread (agent stream)
      description: "The server builds In-Reply-To/References and defaults recipients + subject from the conversation, a minimal call is {\"text\": \"...\"}. Guarded by the reply-loop detector (≥5 outbound/10min → 429 + agent.loop_detected). Idempotency-Key required."
      x-required-scope: inboxes:write
      parameters:
        - { name: threadID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 255 } }
      responses:
        "202": { description: "Queued", content: { application/json: { schema: { $ref: '#/components/schemas/AgentSendResult' } } } }

  /v1/threads/{threadID}/drafts:
    post:
      operationId: createReplyDraft
      tags: [drafts]
      summary: Propose a reply as a draft
      description: "The safe default over /reply: the deterministic policy engine auto-sends clean in-thread replies and holds anything risky (PII, new recipients, injection-flagged threads, always-approve mailboxes) for human approval. A key with inboxes:draft but not inboxes:write may only propose: its clean drafts are held too, never auto-sent. Fires draft.pending_approval when held. Idempotency-Key required."
      x-required-scope: inboxes:draft
      parameters:
        - { name: threadID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 255 } }
      responses:
        "202": { description: "Outcome (sent | pending_approval) with policy_flags", content: { application/json: { schema: { $ref: '#/components/schemas/DraftResult' } } } }

  /v1/threads/{threadID}/classify:
    post:
      operationId: classifyThread
      tags: [ai]
      summary: LLM-classify a thread
      description: "Returns {intent, urgency, summary, suggested_action} via the tenant's AI tier (BYOK or prepaid units, see /v1/ai-config). Cached per thread state: unchanged threads return the cache free; ?refresh=true forces a re-run. A failed model call charges nothing. 402 when the AI tier is off."
      x-required-scope: inboxes:read
      parameters:
        - { name: threadID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: refresh, in: query, schema: { type: boolean } }
      responses:
        "200": { description: "Classification", content: { application/json: { schema: { $ref: '#/components/schemas/ThreadClassification' } } } }
        "402": { description: "AI tier not enabled / out of units" }

  /v1/threads/{threadID}/messages/{messageID}:
    get:
      operationId: getThreadMessage
      tags: [agents]
      summary: Get one message with body
      description: Full text/html body fetched on demand from mail storage. Never marks the message read.
      x-required-scope: inboxes:read
      parameters:
        - { name: threadID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: messageID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        "200": { description: "Message with body", content: { application/json: { schema: { $ref: '#/components/schemas/ThreadMessageBody' } } } }

  /v1/threads/{threadID}/messages/{messageID}/read:
    post:
      operationId: markThreadMessageRead
      tags: [agents]
      summary: Mark read/unread
      description: "The ONLY way agent access changes unread state. Body: {\"read\": true|false} (default true)."
      x-required-scope: inboxes:write
      parameters:
        - { name: threadID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: messageID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        "200": { description: "New read state", content: { application/json: { schema: { $ref: '#/components/schemas/MarkReadResult' } } } }

  /v1/threads/{threadID}/messages/{messageID}/attachments/{idx}:
    get:
      operationId: downloadThreadAttachment
      tags: [agents]
      summary: Download an attachment
      x-required-scope: inboxes:read
      parameters:
        - { name: threadID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: messageID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: idx, in: path, required: true, schema: { type: integer, minimum: 0 } }
      responses:
        "200": { description: "Attachment content (streamed)" }

  /v1/drafts:
    get:
      operationId: listDrafts
      tags: [drafts]
      summary: List drafts
      description: "Filter with ?status=pending_approval|sent|rejected|cancelled. Keys see drafts of granted mailboxes; admin sessions see all."
      x-required-scope: inboxes:read
      parameters:
        - { name: status, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, default: 50, maximum: 200 } }
      responses:
        "200": { description: "Drafts", content: { application/json: { schema: { $ref: '#/components/schemas/DraftList' } } } }

  /v1/drafts/{draftID}:
    get:
      operationId: getDraft
      tags: [drafts]
      summary: Get a draft
      x-required-scope: inboxes:read
      parameters:
        - { name: draftID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        "200": { description: "Draft", content: { application/json: { schema: { $ref: '#/components/schemas/Draft' } } } }

  /v1/drafts/{draftID}/approve:
    post:
      operationId: approveDraft
      tags: [drafts]
      summary: Approve a pending draft (human)
      description: Sends the draft exactly as reviewed, through the agent stream (loop detector included). Fires draft.approved.
      x-required-scope: tenant:admin
      parameters:
        - { name: draftID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        "200": { description: "Sent", content: { application/json: { schema: { $ref: '#/components/schemas/DraftResult' } } } }

  /v1/drafts/{draftID}/reject:
    post:
      operationId: rejectDraft
      tags: [drafts]
      summary: Reject a pending draft (human)
      description: "Body: {\"reason\": \"...\"} (optional). Fires draft.rejected."
      x-required-scope: tenant:admin
      parameters:
        - { name: draftID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        "200": { description: "Rejected", content: { application/json: { schema: { $ref: '#/components/schemas/Draft' } } } }

  /v1/drafts/{draftID}/cancel:
    post:
      operationId: cancelDraft
      tags: [drafts]
      summary: Withdraw a pending draft
      description: Only the API key that created the draft may cancel it.
      x-required-scope: inboxes:write
      parameters:
        - { name: draftID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        "200": { description: "Cancelled", content: { application/json: { schema: { $ref: '#/components/schemas/Draft' } } } }

  /v1/tracking:
    get:
      operationId: getTrackingPolicy
      tags: [tenant]
      summary: Get the engagement tracking policy
      description: |
        Whether open and click tracking are enabled for this account. **Both
        are off until switched on**, and an account that has never set a policy
        reads as off rather than as an error.

        `configured` reports whether this deployment holds a signing secret.
        Without one no tracking token can be minted or verified, so tracking
        cannot work however the flags are set, and a caller seeing
        `track_opens: true` with nothing arriving deserves to know why.
      x-required-scope: tenant:admin
      responses:
        '200':
          description: The policy.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TrackingPolicy' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    put:
      operationId: updateTrackingPolicy
      tags: [tenant]
      summary: Update the engagement tracking policy
      description: |
        Enables or disables tracking for the account. Send either flag or both;
        an omitted flag is left unchanged rather than reset.

        **Enabling this changes what Lockally collects about your recipients**,
        who have no relationship with us. You are the controller for them. What
        is collected is a user-agent string, a timestamp, and for a click the
        destination URL: **no IP address**, ever. The change is written to your
        audit log.
      x-required-scope: tenant:admin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                track_opens: { type: boolean }
                track_clicks: { type: boolean }
      responses:
        '200':
          description: The updated policy.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TrackingPolicy' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/api-keys/{id}/rotate:
    post:
      operationId: rotateApiKey
      tags: [api-keys]
      summary: Rotate an API key
      description: |
        Issues a successor key and puts a short expiry on this one, so **both
        work until the overlap ends**. That window is the point: without it,
        rotation is revocation with extra steps and every caller has to swap
        credentials in the same instant.

        The successor inherits this key's scopes, its label (the label names
        the integration, and the integration has not changed) and its test
        flag. Its full `secret` is in this response and nowhere else.

        The response's `expires_at` is the **predecessor's** deadline, so you
        can see from the rotation itself how long you have to cut over.

        A key that has already been rotated cannot be rotated again: chaining
        overlaps would leave several live keys for one integration, which is
        the opposite of the intent. Rotate the successor instead.
      x-required-scope: tenant:admin
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                grace_seconds:
                  type: integer
                  minimum: 0
                  maximum: 2592000
                  default: 86400
                  description: |
                    How long the old key keeps working. Defaults to 24 hours,
                    which is long enough to cut over without a scramble.
                    Capped at 30 days, because beyond that "rotated" stops
                    meaning anything.
      responses:
        '201':
          description: The successor key. Its `secret` is shown only here; `expires_at` is the predecessor's deadline.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/APIKey'
                  - type: object
                    required: [secret]
                    properties:
                      secret:
                        type: string
                        description: The full token for the SUCCESSOR key. Shown ONCE.
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: The key is revoked, or was already rotated.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/api-keys/{keyID}/mailboxes:
    get:
      operationId: listApiKeyMailboxes
      tags: [agents]
      summary: List a key's mailbox grants
      x-required-scope: tenant:admin
      parameters:
        - { name: keyID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        "200": { description: "Grants", content: { application/json: { schema: { $ref: '#/components/schemas/MailboxGrantList' } } } }
    post:
      operationId: grantApiKeyMailbox
      tags: [agents]
      summary: Grant a mailbox to a key
      description: "Body: {\"mailbox\": \"email or id\"}. Refused (422) for mailboxes with agent access disabled or an active E2E encryption key, the server cannot read E2E mailboxes."
      x-required-scope: tenant:admin
      parameters:
        - { name: keyID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        "201": { description: "Grant created", content: { application/json: { schema: { $ref: '#/components/schemas/MailboxGrant' } } } }
        "422": { description: "Mailbox not grantable (disabled or E2E)" }

  /v1/api-keys/{keyID}/mailboxes/{mailboxID}:
    delete:
      operationId: revokeApiKeyMailbox
      tags: [agents]
      summary: Revoke a mailbox grant
      x-required-scope: tenant:admin
      parameters:
        - { name: keyID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: mailboxID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        "204": { description: "Grant removed" }

  /v1/ai-config:
    get:
      operationId: getAiConfig
      tags: [ai]
      summary: Read the tenant's AI configuration
      description: Mode (off/byok/units), model, masked key hint, AI-unit balance, whether the units tier is available on this deployment.
      x-required-scope: tenant:read
      responses:
        "200": { description: "AI config", content: { application/json: { schema: { $ref: '#/components/schemas/AiConfig' } } } }
    put:
      operationId: updateAiConfig
      tags: [ai]
      summary: Configure the AI tier
      description: "Body: {\"mode\": \"off|byok|units\", \"model\": \"...\", \"anthropic_key\": \"sk-ant-...\"}. BYOK keys are stored AES-256-GCM encrypted; the cleartext is never returned. Omit anthropic_key to keep the stored one."
      x-required-scope: tenant:admin
      responses:
        "200": { description: "Applied", content: { application/json: { schema: { $ref: '#/components/schemas/AiConfigUpdate' } } } }

  /v1/billing/ai-units/checkout:
    post:
      operationId: createAiUnitsCheckout
      tags: [ai]
      summary: Buy prepaid AI units
      description: "Body: {\"bundle\": \"300|1500|6000\"}. One classification = one unit; bundles expire after 3 months. Admin session required. 503 until Paystack billing is configured; 409 while prepaid AI units are not available on this server."
      x-required-scope: tenant:admin
      responses:
        "200":
          description: Paystack authorization URL for the selected AI unit bundle.
          content:
            application/json:
              schema:
                type: object
                required: [authorization_url, reference]
                properties:
                  authorization_url: { type: string, format: uri }
                  reference:         { type: string }
                  units:             { type: integer }

  /v1/test/inbound:
    post:
      operationId: simulateInboundEmail
      tags: [test]
      summary: Simulate an inbound email (test keys only)
      description: "Runs a synthetic message through the REAL indexing pipeline, thread adoption, deterministic extraction (incl. injection_risk), and the message.received webhook, so the whole agent loop is testable without a real domain or MTA. Requires an lk_test_* key (create with {\"test\": true} on POST /v1/api-keys). Body: {mailbox, from, subject, text, in_reply_to?, references?}."
      x-required-scope: inboxes:write
      responses:
        "201": { description: "Simulated message indexed (thread_id, annotations)", content: { application/json: { schema: { $ref: '#/components/schemas/SimulatedInbound' } } } }
        "403": { description: "Live key used, test keys only" }


  # ──────────────────────────────────────────────────────────
  # TAG: users
  # ──────────────────────────────────────────────────────────

  /v1/users:
    get:
      tags: [users]
      summary: List users
      operationId: listUsers
      x-required-scope: tenant:admin
      parameters:
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 1000, default: 100 } }
      responses:
        '200':
          description: User list.
          content:
            application/json:
              schema:
                type: object
                required: [data, limit]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/User' }
                  limit: { type: integer }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

    post:
      tags: [users]
      summary: Create a user
      operationId: createUser
      x-required-scope: tenant:admin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, first_name, last_name]
              properties:
                email:      { type: string, format: email }
                first_name: { type: string }
                last_name:  { type: string }
                title:      { type: string }
                department: { type: string }
      responses:
        '201':
          description: User created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/User' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '409':
          description: Duplicate email address.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/users/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: string, format: uuid } }

    get:
      tags: [users]
      summary: Get a user
      operationId: getUser
      x-required-scope: tenant:admin
      responses:
        '200':
          description: User info.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/User' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

    patch:
      tags: [users]
      summary: Update a user
      description: |
        Setting `status` to `suspended` or `deprovisioned` takes away everything
        the person signs in with: each of their mailboxes and their console
        membership is disabled, app passwords are revoked, and every webmail and
        console session ends. Setting it back to `active` restores what the
        suspension disabled, and nothing an admin disabled for another reason.
        API keys belong to the workspace, not to the person who created them,
        and are not revoked; rotate any the person had access to.
      operationId: updateUser
      x-required-scope: tenant:admin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                first_name: { type: string }
                last_name:  { type: string }
                title:      { type: string }
                department: { type: string }
                status:
                  type: string
                  enum: [active, suspended, deprovisioned]
      responses:
        '200':
          description: Updated user.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/User' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: The person is the caller, or the workspace's last active admin.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

    delete:
      tags: [users]
      summary: Deprovision a user
      description: |
        Sets the user's status to `deprovisioned` and ends their access: each
        of their mailboxes and their console membership is disabled, app
        passwords are revoked, and every webmail and console session ends. Their
        mail is kept. API keys belong to the workspace and are not revoked;
        rotate any the person had access to.
      operationId: deleteUser
      x-required-scope: tenant:admin
      responses:
        '204': { description: No content }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: The person is the caller, or the workspace's last active admin.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  # ──────────────────────────────────────────────────────────
  # TAG: billing
  # ──────────────────────────────────────────────────────────

  /v1/billing:
    get:
      tags: [billing]
      summary: Get billing status
      operationId: getBilling
      x-required-scope: tenant:read
      responses:
        '200':
          description: Current billing status.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BillingStatus' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/billing/checkout:
    post:
      tags: [billing]
      summary: Create a plan checkout session
      operationId: createBillingCheckout
      x-required-scope: tenant:admin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [plan]
              properties:
                plan:
                  type: string
                  enum: [free, founder, starter, pro, scale]
      responses:
        '200':
          description: Checkout URL for payment.
          content:
            application/json:
              schema:
                type: object
                required: [authorization_url, reference]
                properties:
                  authorization_url: { type: string, format: uri }
                  reference:         { type: string }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/billing/units/checkout:
    post:
      tags: [billing]
      summary: Create a send-units checkout session
      operationId: createUnitsCheckout
      x-required-scope: tenant:admin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [bundle]
              properties:
                bundle:
                  type: string
                  enum: [1k, 10k, 50k, 100k, 1pkt, 5pkt, 10pkt, 20pkt]
      responses:
        '200':
          description: Checkout URL for the selected unit bundle.
          content:
            application/json:
              schema:
                type: object
                required: [authorization_url, reference, units]
                properties:
                  authorization_url: { type: string, format: uri }
                  reference:         { type: string }
                  units:             { type: integer }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  # ──────────────────────────────────────────────────────────
  # TAG: add-ons
  # ──────────────────────────────────────────────────────────

  /v1/add-ons:
    get:
      tags: [add-ons]
      summary: List add-ons
      operationId: listAddOns
      x-required-scope: tenant:read
      responses:
        '200':
          description: Available add-ons and their activation state.
          content:
            application/json:
              schema:
                type: object
                required: [add_ons]
                properties:
                  add_ons:
                    type: array
                    items: { $ref: '#/components/schemas/AddOn' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/add-ons/{name}:
    parameters:
      - { name: name, in: path, required: true, schema: { type: string }, description: Add-on key }

    get:
      tags: [add-ons]
      summary: Get add-on status
      operationId: getAddOnStatus
      x-required-scope: tenant:read
      responses:
        '200':
          description: Add-on eligibility and activation state.
          content:
            application/json:
              schema:
                type: object
                required: [name, eligible, active]
                properties:
                  name:     { type: string }
                  eligible: { type: boolean }
                  active:   { type: boolean }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/add-ons/{name}/activate:
    parameters:
      - { name: name, in: path, required: true, schema: { type: string }, description: Add-on key }

    post:
      tags: [add-ons]
      summary: Activate an add-on
      operationId: activateAddOn
      x-required-scope: tenant:admin
      responses:
        '200':
          description: Add-on activated.
          content:
            application/json:
              schema:
                type: object
                required: [id, add_on, status, message]
                properties:
                  id:      { type: string, format: uuid }
                  add_on:  { type: string }
                  status:  { type: string }
                  message: { type: string }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/add-ons/{name}/cancel:
    parameters:
      - { name: name, in: path, required: true, schema: { type: string }, description: Add-on key }

    post:
      tags: [add-ons]
      summary: Cancel an add-on
      operationId: cancelAddOn
      x-required-scope: tenant:admin
      responses:
        '204': { description: No content }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  # ──────────────────────────────────────────────────────────
  # TAG: mailboxes (shared-members sub-resource)
  # ──────────────────────────────────────────────────────────

  /v1/mailboxes/{email}/members:
    parameters:
      - { name: email, in: path, required: true, schema: { type: string, format: email } }

    get:
      tags: [mailboxes]
      summary: List shared mailbox members
      operationId: listSharedMembers
      x-required-scope: mailboxes:read
      responses:
        '200':
          description: Members of the shared mailbox.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/SharedMember' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

    post:
      tags: [mailboxes]
      summary: Add a shared mailbox member
      operationId: addSharedMember
      x-required-scope: mailboxes:write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [member_email]
              properties:
                member_email: { type: string, format: email }
                role:
                  type: string
                  enum: [manager, member]
                  default: member
      responses:
        '201':
          description: Member added.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SharedMember' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Already a member of this mailbox.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/mailboxes/{email}/members/{memberEmail}:
    parameters:
      - { name: email, in: path, required: true, schema: { type: string, format: email } }
      - { name: memberEmail, in: path, required: true, schema: { type: string, format: email } }

    delete:
      tags: [mailboxes]
      summary: Remove a shared mailbox member
      operationId: removeSharedMember
      x-required-scope: mailboxes:write
      responses:
        '204': { description: No content }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  # ──────────────────────────────────────────────────────────
  # TAG: distribution-lists
  # ──────────────────────────────────────────────────────────

  /v1/distribution-lists:
    get:
      tags: [distribution-lists]
      summary: List distribution lists
      operationId: listDistributionLists
      x-required-scope: mailboxes:read
      responses:
        '200':
          description: All distribution lists for the tenant.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/DistributionListSummary' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

    post:
      tags: [distribution-lists]
      summary: Create a distribution list
      operationId: createDistributionList
      x-required-scope: mailboxes:write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [list_address]
              properties:
                list_address: { type: string, format: email }
                name:         { type: string }
                members:
                  type: array
                  items: { type: string, format: email }
      responses:
        '201':
          description: Distribution list created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DistributionListDetail' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '409':
          description: List address already exists.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  /v1/distribution-lists/{address}:
    parameters:
      - { name: address, in: path, required: true, schema: { type: string }, description: Distribution list email address }

    get:
      tags: [distribution-lists]
      summary: Get a distribution list
      operationId: getDistributionList
      x-required-scope: mailboxes:read
      responses:
        '200':
          description: Distribution list with full member list.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DistributionListDetail' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

    delete:
      tags: [distribution-lists]
      summary: Delete a distribution list
      operationId: deleteDistributionList
      x-required-scope: mailboxes:write
      responses:
        '204': { description: No content }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/distribution-lists/{address}/members:
    parameters:
      - { name: address, in: path, required: true, schema: { type: string }, description: Distribution list email address }

    put:
      tags: [distribution-lists]
      summary: Replace distribution list members
      operationId: replaceDistributionListMembers
      x-required-scope: mailboxes:write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [members]
              properties:
                members:
                  type: array
                  items: { type: string, format: email }
      responses:
        '200':
          description: Updated member list.
          content:
            application/json:
              schema:
                type: object
                required: [id, tenant_id, list_address, members, member_count]
                properties:
                  id:           { type: string, format: uuid }
                  tenant_id:    { type: string, format: uuid }
                  list_address: { type: string }
                  members:
                    type: array
                    items: { type: string }
                  member_count: { type: integer }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  # ──────────────────────────────────────────────────────────
  # TAG: signup
  # ──────────────────────────────────────────────────────────

  /v1/signup:
    post:
      tags: [signup]
      summary: Sign up a new tenant
      operationId: signup
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [slug, admin_email, password]
              properties:
                slug:
                  type: string
                  description: >-
                    Workspace id. 3 to 63 characters of lowercase a-z, 0-9 and
                    hyphens, starting and ending with a letter or digit. Anything
                    else is refused with 400 Invalid workspace id.
                display_name: { type: string }
                admin_email:  { type: string, format: email }
                password:     { type: string, minLength: 12 }
                mode:
                  type: string
                  enum: [api, business, both]
                  default: business
      responses:
        '201':
          description: Tenant created with initial admin and API token.
          content:
            application/json:
              schema:
                type: object
                required: [token, expires_at, admin, tenant]
                properties:
                  token:      { type: string }
                  expires_at: { type: string, format: date-time }
                  admin:      { $ref: '#/components/schemas/Admin' }
                  tenant:     { $ref: '#/components/schemas/Tenant' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '409':
          description: Slug or email already taken.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

  # ──────────────────────────────────────────────────────────
  # TAG: ip-pools
  # ──────────────────────────────────────────────────────────

  /v1/ip-assignment:
    get:
      tags: [ip-pools]
      summary: Get current IP assignment
      operationId: getIPAssignment
      x-required-scope: tenant:read
      responses:
        '200':
          description: The tenant's current outbound IP assignment.
          content:
            application/json:
              schema:
                type: object
                properties:
                  pool_name:    { type: string, nullable: true }
                  pool_kind:    { type: string, nullable: true }
                  dedicated_ip: { type: string, nullable: true }
                  assigned_at:  { type: string, format: date-time, nullable: true }
                  reason:       { type: string, nullable: true }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/dedicated-ip-requests:
    post:
      tags: [ip-pools]
      summary: Request a dedicated IP
      operationId: createDedicatedIPRequest
      x-required-scope: tenant:admin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [note]
              properties:
                note: { type: string }
      responses:
        '201':
          description: Dedicated IP request submitted.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DedicatedIPRequest' }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '409':
          description: A pending request already exists.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }

    get:
      tags: [ip-pools]
      summary: List dedicated IP requests
      operationId: listDedicatedIPRequests
      x-required-scope: tenant:read
      responses:
        '200':
          description: Dedicated IP request history.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/DedicatedIPRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }


  /v1/calendars:
    post:
      tags: [calendars]
      operationId: createCalendar
      x-required-scope: mailboxes:write
      summary: Create a calendar
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string }
                color: { type: string }
                owner_email: { type: string, format: email }
                description: { type: string }
                visibility:
                  type: string
                  enum: [private, tenant]
                  default: tenant
      responses:
        '201':
          description: Calendar created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Calendar'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    get:
      tags: [calendars]
      operationId: listCalendars
      x-required-scope: mailboxes:read
      summary: List calendars
      responses:
        '200':
          description: List of calendars
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Calendar'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/calendars/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [calendars]
      operationId: getCalendar
      x-required-scope: mailboxes:read
      summary: Get a calendar
      responses:
        '200':
          description: Calendar details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Calendar'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    patch:
      tags: [calendars]
      operationId: updateCalendar
      x-required-scope: mailboxes:write
      summary: Update a calendar
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                color: { type: string }
                owner_email: { type: string, format: email }
                description: { type: string }
                visibility:
                  type: string
                  enum: [private, tenant]
      responses:
        '200':
          description: Calendar updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Calendar'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    delete:
      tags: [calendars]
      operationId: deleteCalendar
      x-required-scope: mailboxes:write
      summary: Delete a calendar
      responses:
        '204': { description: No content }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/calendars/{id}/events:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [calendars]
      operationId: listCalendarEvents
      x-required-scope: mailboxes:read
      summary: List events in a calendar
      parameters:
        - name: from
          in: query
          schema: { type: string, format: date-time }
        - name: to
          in: query
          schema: { type: string, format: date-time }
      responses:
        '200':
          description: List of calendar events
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/CalendarEvent'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    post:
      tags: [calendars]
      operationId: createCalendarEvent
      x-required-scope: mailboxes:write
      summary: Create an event in a calendar
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [title, starts_at, ends_at]
              properties:
                title: { type: string }
                description: { type: string }
                location: { type: string }
                starts_at: { type: string, format: date-time }
                ends_at: { type: string, format: date-time }
                all_day: { type: boolean, default: false }
      responses:
        '201':
          description: Event created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalendarEvent'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/calendars/{id}/events/{eventId}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
      - name: eventId
        in: path
        required: true
        schema: { type: string, format: uuid }
    patch:
      tags: [calendars]
      operationId: updateCalendarEvent
      x-required-scope: mailboxes:write
      summary: Update a calendar event
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                title: { type: string }
                description: { type: string }
                location: { type: string }
                starts_at: { type: string, format: date-time }
                ends_at: { type: string, format: date-time }
                all_day: { type: boolean }
      responses:
        '200':
          description: Event updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalendarEvent'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    delete:
      tags: [calendars]
      operationId: deleteCalendarEvent
      x-required-scope: mailboxes:write
      summary: Delete a calendar event
      responses:
        '204': { description: No content }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/calendars/{id}/members:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [calendars]
      operationId: listCalendarMembers
      x-required-scope: mailboxes:read
      summary: List calendar members
      responses:
        '200':
          description: List of calendar members
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/CalendarMember'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    post:
      tags: [calendars]
      operationId: addCalendarMember
      x-required-scope: mailboxes:write
      summary: Add a member to a calendar
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [user_email]
              properties:
                user_email: { type: string, format: email }
                role:
                  type: string
                  enum: [viewer, editor, owner]
                  default: viewer
      responses:
        '201':
          description: Member added
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalendarMember'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/calendars/{id}/members/{memberId}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
      - name: memberId
        in: path
        required: true
        schema: { type: string, format: uuid }
    patch:
      tags: [calendars]
      operationId: updateCalendarMember
      x-required-scope: mailboxes:write
      summary: Update a calendar member's role
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [role]
              properties:
                role:
                  type: string
                  enum: [viewer, editor, owner]
      responses:
        '200':
          description: Member updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalendarMember'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    delete:
      tags: [calendars]
      operationId: removeCalendarMember
      x-required-scope: mailboxes:write
      summary: Remove a member from a calendar
      responses:
        '204': { description: No content }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/calendar-policies:
    get:
      tags: [calendars]
      operationId: getCalendarPolicies
      x-required-scope: mailboxes:read
      summary: Get calendar policies
      responses:
        '200':
          description: Calendar policies
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalendarPolicies'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    patch:
      tags: [calendars]
      operationId: updateCalendarPolicies
      x-required-scope: mailboxes:write
      summary: Update calendar policies
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                max_meeting_duration_mins: { type: integer, minimum: 15, maximum: 1440 }
                working_hours_start: { type: string }
                working_hours_end: { type: string }
                booking_window_days: { type: integer, minimum: 1, maximum: 365 }
                recurring_meeting_limit: { type: integer, minimum: 1, maximum: 365 }
                resource_approval_mode:
                  type: string
                  enum: [auto_approve, require_approval, restricted]
                external_invites_allowed: { type: boolean }
                external_sharing_allowed: { type: boolean }
                public_links_enabled: { type: boolean }
      responses:
        '200':
          description: Calendar policies updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalendarPolicies'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/calendar-security:
    get:
      tags: [calendars]
      operationId: getCalendarSecurity
      x-required-scope: mailboxes:read
      summary: Get calendar security overview
      responses:
        '200':
          description: Calendar security overview
          content:
            application/json:
              schema:
                type: object
                properties:
                  total_calendars: { type: integer }
                  public_calendars: { type: integer }
                  private_calendars: { type: integer }
                  total_members: { type: integer }
                  delegated_access:
                    type: array
                    items:
                      type: object
                      properties:
                        calendar_id: { type: string, format: uuid }
                        calendar_name: { type: string }
                        user_email: { type: string }
                        role: { type: string }
                        granted_at: { type: string, format: date-time }
                  public_calendar_list:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string, format: uuid }
                        name: { type: string }
                        owner_email: { type: string }
                        member_count: { type: integer }
                        has_feed: { type: boolean }
                  alerts:
                    type: array
                    items:
                      type: object
                      properties:
                        level:
                          type: string
                          enum: [critical, warning]
                        message: { type: string }
                  external_sharing:
                    type: object
                    properties:
                      invites_allowed: { type: boolean }
                      sharing_allowed: { type: boolean }
                      public_links: { type: boolean }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/calendar-overview:
    get:
      tags: [calendars]
      operationId: getCalendarOverview
      x-required-scope: mailboxes:read
      summary: Administrative overview of the organization's calendar system
      description: |
        Counts across the whole account, plus the recent calendar entries from
        the audit trail. Not scoped to the caller's own calendar.
      responses:
        '200':
          description: Calendar overview
          content:
            application/json:
              schema:
                type: object
                properties:
                  total_calendars: { type: integer }
                  active_calendars:
                    type: integer
                    description: Calendars with an event created, edited or held in the last 30 days.
                  shared_calendars:
                    type: integer
                    description: Calendars visible to the whole organization.
                  events_this_month:
                    type: integer
                    description: Events on every calendar, in the account's own timezone.
                  upcoming_org_events:
                    type: integer
                    description: Future events on organization-visible calendars.
                  bookable_resources:
                    type: integer
                    description: Resources that are not disabled.
                  access_granted:
                    type: integer
                    description: People who own a calendar or are named on one.
                  access_org_wide:
                    type: integer
                    description: Everyone who can see an organization calendar; 0 when none exists.
                  activity:
                    type: array
                    items:
                      type: object
                      properties:
                        action: { type: string }
                        target: { type: string }
                        actor: { type: string }
                        created_at: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/calendar-integrations:
    get:
      tags: [calendars]
      operationId: listCalendarIntegrations
      x-required-scope: mailboxes:read
      summary: List calendar integrations
      responses:
        '200':
          description: List of calendar integrations
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/CalendarIntegration'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    post:
      tags: [calendars]
      operationId: createCalendarIntegration
      x-required-scope: mailboxes:write
      summary: Create a calendar integration
      description: |
        Not implemented. Calendar integrations do not sync with any provider
        yet, so this always answers 501. Listing and deleting still work, for
        entries created before the feature was withdrawn.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [provider]
              properties:
                provider:
                  type: string
                  enum: [exchange, google_calendar, teams, zoom, erp]
                label: { type: string }
      responses:
        '201':
          description: Integration created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalendarIntegration'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '501': { description: Calendar integrations are not available yet }

  /v1/calendar-integrations/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    patch:
      tags: [calendars]
      operationId: updateCalendarIntegration
      x-required-scope: mailboxes:write
      summary: Update a calendar integration
      description: |
        Not implemented. Calendar integrations do not sync with any provider
        yet, so this always answers 501. Listing and deleting still work, for
        entries created before the feature was withdrawn.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                label: { type: string }
                status:
                  type: string
                  enum: [connected, disconnected, error, syncing]
                error_message: { type: string }
      responses:
        '200':
          description: Integration updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalendarIntegration'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '501': { description: Calendar integrations are not available yet }
    delete:
      tags: [calendars]
      operationId: deleteCalendarIntegration
      x-required-scope: mailboxes:write
      summary: Delete a calendar integration
      responses:
        '204': { description: No content }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/calendar-integrations/{id}/sync:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      tags: [calendars]
      operationId: syncCalendarIntegration
      x-required-scope: mailboxes:write
      summary: Trigger sync for a calendar integration
      description: |
        Not implemented. Calendar integrations do not sync with any provider
        yet, so this always answers 501. Listing and deleting still work, for
        entries created before the feature was withdrawn.
      responses:
        '200':
          description: Sync initiated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalendarIntegration'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '501': { description: Calendar integrations are not available yet }

  /v1/resources:
    get:
      tags: [resources]
      operationId: listResources
      x-required-scope: mailboxes:read
      summary: List resources
      responses:
        '200':
          description: List of resources
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Resource'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    post:
      tags: [resources]
      operationId: createResource
      x-required-scope: mailboxes:write
      summary: Create a resource
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string }
                type:
                  type: string
                  enum: [meeting_room, equipment]
                  default: meeting_room
                capacity: { type: integer, minimum: 0, nullable: true }
      responses:
        '201':
          description: Resource created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Resource'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/resources/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [resources]
      operationId: getResource
      x-required-scope: mailboxes:read
      summary: Get a resource
      responses:
        '200':
          description: Resource details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Resource'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    patch:
      tags: [resources]
      operationId: updateResource
      x-required-scope: mailboxes:write
      summary: Update a resource
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                type:
                  type: string
                  enum: [meeting_room, equipment]
                capacity: { type: integer }
                status:
                  type: string
                  enum: [available, active, disabled]
      responses:
        '200':
          description: Resource updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Resource'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    delete:
      tags: [resources]
      operationId: deleteResource
      x-required-scope: mailboxes:write
      summary: Delete a resource
      responses:
        '204': { description: No content }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }


  /v1/contacts:
    get:
      tags: [contacts]
      operationId: listContacts
      x-required-scope: mailboxes:read
      summary: List contacts
      parameters:
        - name: q
          in: query
          schema: { type: string }
          description: Free-text search across name, email, company
        - name: type
          in: query
          schema: { type: string }
          description: Filter by contact_type
        - name: department
          in: query
          schema: { type: string }
          description: Filter by department
        - name: status
          in: query
          schema: { type: string }
          description: Filter by status
        - name: source
          in: query
          schema: { type: string }
          description: Filter by source
      responses:
        '200':
          description: List of contacts
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Contact'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    post:
      tags: [contacts]
      operationId: createContact
      x-required-scope: mailboxes:write
      summary: Create a contact
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, email]
              properties:
                name: { type: string }
                email: { type: string, format: email }
                phone: { type: string }
                company: { type: string }
                notes: { type: string }
                contact_type:
                  type: string
                  enum: [internal, external]
                  default: external
                department: { type: string }
                role: { type: string }
      responses:
        '201':
          description: Contact created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Contact'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/contacts/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [contacts]
      operationId: getContact
      x-required-scope: mailboxes:read
      summary: Get a contact
      responses:
        '200':
          description: Contact details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Contact'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    patch:
      tags: [contacts]
      operationId: updateContact
      x-required-scope: mailboxes:write
      summary: Update a contact
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                email: { type: string, format: email }
                phone: { type: string }
                company: { type: string }
                notes: { type: string }
                contact_type:
                  type: string
                  enum: [internal, external]
                department: { type: string }
                role: { type: string }
                status:
                  type: string
                  enum: [active, disabled]
      responses:
        '200':
          description: Contact updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Contact'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    delete:
      tags: [contacts]
      operationId: deleteContact
      x-required-scope: mailboxes:write
      summary: Delete a contact
      responses:
        '204':
          description: Contact deleted
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/contacts/{id}/lists:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [contacts]
      operationId: getContactLists
      x-required-scope: mailboxes:read
      summary: Get lists a contact belongs to
      responses:
        '200':
          description: Lists containing this contact
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string, format: uuid }
                        name: { type: string }
                        visibility: { type: string }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/contacts/external/{system}/{external_id}:
    parameters:
      - name: system
        in: path
        required: true
        description: >-
          Your label for the system the record comes from, for example
          `salesforce`, `hubspot` or `odoo`. 1 to 64 characters: lowercase
          letters, digits, dot, underscore or hyphen (upper case is folded).
        schema: { type: string, pattern: '^[a-z0-9][a-z0-9._-]{0,63}$' }
      - name: external_id
        in: path
        required: true
        description: >-
          The record's id in that system, kept exactly as given (case
          matters). 1 to 255 characters, no spaces. URL-encode it.
        schema: { type: string, maxLength: 255 }
    put:
      tags: [contacts]
      operationId: upsertExternalContact
      x-required-scope: contacts:write
      summary: Create or update a contact by its id in another system
      description: >-
        Idempotent: the path is the identity, so sending the same request
        twice cannot create a second contact, and you never need to store our
        id. Returns 201 when the contact was created and 200 when it already
        existed. The body is the full representation: a field you leave out
        is cleared. Email is an ordinary attribute, not a key, so changing it
        updates the same contact. `mailboxes:write` is also accepted.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExternalContactInput'
      responses:
        '200':
          description: The contact already existed and was updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Contact'
        '201':
          description: The contact was created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Contact'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    get:
      tags: [contacts]
      operationId: getExternalContact
      x-required-scope: contacts:read
      summary: Get a contact by its id in another system
      responses:
        '200':
          description: Contact details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Contact'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    delete:
      tags: [contacts]
      operationId: deleteExternalContact
      x-required-scope: contacts:write
      summary: Delete a contact by its id in another system
      responses:
        '204':
          description: Contact deleted
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/contacts/external/{system}:
    parameters:
      - name: system
        in: path
        required: true
        schema: { type: string, pattern: '^[a-z0-9][a-z0-9._-]{0,63}$' }
    put:
      tags: [contacts]
      operationId: bulkUpsertExternalContacts
      x-required-scope: contacts:write
      summary: Create or update up to 500 contacts by their ids in another system
      description: >-
        For a sync. Each row stands alone: a bad row is reported in `results`
        with its index and the rest are stored, so the response is 200 whenever
        the request itself is well formed. Read `failed` and `results`. Two
        rows with the same `external_id` in one request are refused (the later
        one), because which is current cannot be known. Rerunning the same
        payload updates rather than duplicates.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [contacts]
              properties:
                contacts:
                  type: array
                  minItems: 1
                  maxItems: 500
                  items:
                    allOf:
                      - $ref: '#/components/schemas/ExternalContactInput'
                      - type: object
                        required: [external_id]
                        properties:
                          external_id: { type: string, maxLength: 255 }
      responses:
        '200':
          description: Per-row results
          content:
            application/json:
              schema:
                type: object
                required: [created, updated, failed, results]
                properties:
                  created: { type: integer }
                  updated: { type: integer }
                  failed: { type: integer }
                  results:
                    type: array
                    items:
                      type: object
                      required: [index, external_id, status]
                      properties:
                        index: { type: integer }
                        external_id: { type: string }
                        status:
                          type: string
                          enum: [created, updated, error]
                        contact:
                          $ref: '#/components/schemas/Contact'
                        error: { type: string }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/contact-lists:
    get:
      tags: [contact-lists]
      operationId: listContactLists
      x-required-scope: mailboxes:read
      summary: List contact lists
      responses:
        '200':
          description: List of contact lists
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/ContactList'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    post:
      tags: [contact-lists]
      operationId: createContactList
      x-required-scope: mailboxes:write
      summary: Create a contact list
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string }
                description: { type: string }
                visibility:
                  type: string
                  enum: [company_wide, restricted]
                  default: company_wide
      responses:
        '201':
          description: Contact list created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ContactList'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/contact-lists/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [contact-lists]
      operationId: getContactList
      x-required-scope: mailboxes:read
      summary: Get a contact list with members
      responses:
        '200':
          description: Contact list with members
          content:
            application/json:
              schema:
                type: object
                properties:
                  list:
                    $ref: '#/components/schemas/ContactList'
                  members:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string, format: uuid }
                        name: { type: string }
                        email: { type: string }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    patch:
      tags: [contact-lists]
      operationId: updateContactList
      x-required-scope: mailboxes:write
      summary: Update a contact list
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                description: { type: string }
                visibility:
                  type: string
                  enum: [company_wide, restricted]
      responses:
        '200':
          description: Contact list updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ContactList'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
    delete:
      tags: [contact-lists]
      operationId: deleteContactList
      x-required-scope: mailboxes:write
      summary: Delete a contact list
      responses:
        '204':
          description: Contact list deleted
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/contact-lists/{id}/members:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      tags: [contact-lists]
      operationId: addContactListMember
      x-required-scope: mailboxes:write
      summary: Add a member to a contact list
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [contact_id]
              properties:
                contact_id: { type: string, format: uuid }
      responses:
        '204':
          description: Member added
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/contact-lists/{id}/members/{contactId}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
      - name: contactId
        in: path
        required: true
        schema: { type: string, format: uuid }
    delete:
      tags: [contact-lists]
      operationId: removeContactListMember
      x-required-scope: mailboxes:write
      summary: Remove a member from a contact list
      responses:
        '204':
          description: Member removed
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/gal-settings:
    get:
      tags: [directory]
      operationId: getGALSettings
      x-required-scope: mailboxes:read
      summary: Get Global Address List settings
      responses:
        '200':
          description: GAL settings
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GALSettings'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    patch:
      tags: [directory]
      operationId: updateGALSettings
      x-required-scope: mailboxes:write
      summary: Update GAL settings
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                gal_enabled: { type: boolean }
                hide_from_directory: { type: boolean }
                department_grouping: { type: boolean }
                search_visibility:
                  type: string
                  enum: [all_users, same_department, admins_only]
                include_external_contacts: { type: boolean }
      responses:
        '200':
          description: GAL settings updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GALSettings'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/gal-settings/rebuild-index:
    post:
      tags: [directory]
      operationId: rebuildGALIndex
      x-required-scope: mailboxes:write
      summary: Rebuild the GAL search index
      responses:
        '200':
          description: GAL settings after index rebuild
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GALSettings'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/gal-settings/sync:
    post:
      tags: [directory]
      operationId: syncGAL
      x-required-scope: mailboxes:write
      summary: Sync GAL with external directory sources
      responses:
        '200':
          description: GAL settings after sync
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GALSettings'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/directory-permissions:
    get:
      tags: [directory]
      operationId: getDirectoryPermissions
      x-required-scope: mailboxes:read
      summary: Get directory permission settings
      responses:
        '200':
          description: Directory permissions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DirectoryPermissions'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
    patch:
      tags: [directory]
      operationId: updateDirectoryPermissions
      x-required-scope: mailboxes:write
      summary: Update directory permission settings
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                contact_view_access:
                  type: string
                  enum: [all_users, same_department, admins_only]
                contact_edit_access:
                  type: string
                  enum: [all_users, admins_only]
                list_manage_access:
                  type: string
                  enum: [all_users, list_owners, admins_only]
                external_sharing:
                  type: string
                  enum: [allowed, restricted, disabled]
      responses:
        '200':
          description: Directory permissions updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DirectoryPermissions'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/directory-stats:
    get:
      tags: [directory]
      operationId: getDirectoryStats
      x-required-scope: mailboxes:read
      summary: Get directory statistics
      responses:
        '200':
          description: Directory statistics
          content:
            application/json:
              schema:
                type: object
                properties:
                  total_contacts: { type: integer }
                  internal_users: { type: integer }
                  external_contacts: { type: integer }
                  synced_contacts: { type: integer }
                  shared_lists: { type: integer }
                  directory_groups: { type: integer }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/directory-activity:
    get:
      tags: [directory]
      operationId: getDirectoryActivity
      x-required-scope: mailboxes:read
      summary: Get recent directory activity
      responses:
        '200':
          description: Recent directory activity
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        type: { type: string }
                        message: { type: string }
                        detail: { type: string, nullable: true }
                        timestamp: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/encryption/keys:
    post:
      tags: [encryption]
      operationId: createEncryptionKey
      x-required-scope: mailboxes:write
      summary: Upload an encryption key pair
      description: >-
        Only the mailbox's own webmail session may call this; an API key is
        refused with 403. The private key is sealed under that mailbox's
        password, which an administrator never has. `mailbox_email`, if sent,
        must be the caller's own mailbox.
        A mailbox that already has a key is starting over: the old key is kept
        inactive, not destroyed, and the new one starts without a recovery code.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [public_key, encrypted_private_key]
              properties:
                mailbox_email: { type: string, format: email }
                public_key: { type: string }
                encrypted_private_key: { type: string }
                kdf_params: { type: object }
      responses:
        '201':
          description: Key pair stored
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  mailbox_id: { type: string, format: uuid }
                  created_at: { type: string, format: date-time }
                  replaced_old: { type: boolean }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/encryption/keys/lookup:
    get:
      tags: [encryption]
      operationId: batchLookupPublicKeys
      x-required-scope: mailboxes:read
      summary: Batch-lookup public keys by email
      parameters:
        - name: emails
          in: query
          required: true
          schema: { type: string }
          description: Comma-separated list of email addresses
      responses:
        '200':
          description: Public keys for requested emails
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        email: { type: string }
                        public_key: { type: string, nullable: true }
                        key_id: { type: string, format: uuid, nullable: true }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/encryption/keys/{email}:
    parameters:
      - name: email
        in: path
        required: true
        schema: { type: string, format: email }
    get:
      tags: [encryption]
      operationId: getEncryptionKey
      x-required-scope: mailboxes:read
      summary: Get encryption key for a mailbox
      description: >-
        Anyone in the workspace gets the public key. The mailbox's own webmail
        session also gets its sealed private key, its sealed recovery copy and
        the recovery state.
      responses:
        '200':
          description: Encryption key details
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  email: { type: string, format: email }
                  public_key: { type: string }
                  encrypted_private_key: { type: string }
                  kdf_params: { type: object }
                  version: { type: integer }
                  created_at: { type: string, format: date-time }
                  rotated_at: { type: string, format: date-time, nullable: true }
                  has_recovery: { type: boolean }
                  recovery_set_at: { type: string, format: date-time, nullable: true }
                  recovery_blob: { type: string }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }

  /v1/encryption/keys/rotate:
    post:
      tags: [encryption]
      operationId: rotateEncryptionKey
      x-required-scope: mailboxes:write
      summary: Re-seal an encryption key under a new password
      description: >-
        Only the mailbox's own webmail session may call this; an API key is
        refused with 403. The private key is sealed under that mailbox's
        password, which an administrator never has. `mailbox_email`, if sent,
        must be the caller's own mailbox.
        The key pair does not change, so every message stays readable.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [encrypted_private_key]
              properties:
                mailbox_email: { type: string, format: email }
                encrypted_private_key: { type: string }
                kdf_params: { type: object }
      responses:
        '204':
          description: Key rotated
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/encryption/status:
    get:
      tags: [encryption]
      operationId: getEncryptionStatus
      x-required-scope: mailboxes:read
      summary: End-to-end encryption status for the workspace
      description: >-
        For administrators: whether the add-on is on, and for each mailbox
        whether it has a key and a recovery code. Carries no key material.
      responses:
        '200':
          description: Status
          content:
            application/json:
              schema:
                type: object
                properties:
                  eligible: { type: boolean }
                  active: { type: boolean }
                  mailboxes:
                    type: array
                    items:
                      type: object
                      properties:
                        email: { type: string, format: email }
                        has_key: { type: boolean }
                        key_created_at: { type: string, format: date-time }
                        has_recovery: { type: boolean }
                        recovery_set_at: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/encryption/recovery:
    post:
      tags: [encryption]
      operationId: createEncryptionRecovery
      x-required-scope: mailboxes:write
      summary: Store an encryption recovery blob
      description: >-
        Only the mailbox's own webmail session may call this; an API key is
        refused with 403. The private key is sealed under that mailbox's
        password, which an administrator never has. `mailbox_email`, if sent,
        must be the caller's own mailbox.
        The blob is the private key sealed under a recovery code the browser
        generated; the code itself is never sent. Replaces any earlier one.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [recovery_blob]
              properties:
                mailbox_email: { type: string, format: email }
                recovery_blob: { type: string }
      responses:
        '204':
          description: Recovery blob stored
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/user-insights:
    get:
      tags: [dashboard]
      operationId: getUserInsights
      x-required-scope: tenant:read
      summary: User insights for the dashboard
      responses:
        '200':
          description: User insights
          content:
            application/json:
              schema:
                type: object
                properties:
                  recently_added:
                    type: array
                    items: { $ref: '#/components/schemas/UserEvent' }
                  recently_suspended:
                    type: array
                    items: { $ref: '#/components/schemas/UserEvent' }
                  inactive_30d:
                    type: array
                    items: { $ref: '#/components/schemas/UserEvent' }
                  seats_used: { type: integer }
                  seats_alloc: { type: integer }
                  seats_capped: { type: boolean, description: "True only on tiers with a hard seat cap (Free, Founder). On unlimited/per-seat tiers seats_alloc merely tracks the live mailbox count, so seats_used == seats_alloc is normal and must not be read as 'at capacity'." }
                  generated_at: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/audit-summary:
    get:
      tags: [dashboard]
      operationId: getAuditSummary
      x-required-scope: tenant:read
      summary: Audit summary for the dashboard
      responses:
        '200':
          description: Audit summary
          content:
            application/json:
              schema:
                type: object
                properties:
                  admin_actions_today: { type: integer }
                  recent_logins:
                    type: array
                    items: { $ref: '#/components/schemas/AuditEvent' }
                  recent_exports:
                    type: array
                    items: { $ref: '#/components/schemas/AuditEvent' }
                  deleted_mailboxes:
                    type: array
                    items: { $ref: '#/components/schemas/AuditEvent' }
                  generated_at: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/integrations-summary:
    get:
      tags: [dashboard]
      operationId: getIntegrationsSummary
      x-required-scope: tenant:read
      summary: Integrations summary for the dashboard
      responses:
        '200':
          description: Integrations summary
          content:
            application/json:
              schema:
                type: object
                properties:
                  api_requests_today: { type: integer }
                  active_api_keys: { type: integer }
                  api_keys:
                    type: array
                    items:
                      type: object
                      properties:
                        label: { type: string }
                        prefix: { type: string }
                        last_used_at: { type: string, format: date-time, nullable: true }
                  webhook_failures: { type: integer }
                  webhooks_total: { type: integer }
                  webhooks:
                    type: array
                    items:
                      type: object
                      properties:
                        url: { type: string, format: uri }
                        paused: { type: boolean }
                        consecutive_failures: { type: integer }
                        last_failure_at: { type: string, format: date-time, nullable: true }
                  generated_at: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/security:
    get:
      tags: [dashboard]
      operationId: getSecurity
      x-required-scope: tenant:read
      summary: Security overview for the dashboard
      responses:
        '200':
          description: Security overview
          content:
            application/json:
              schema:
                type: object
                properties:
                  overall_status:
                    type: string
                    enum: [healthy, warning, critical]
                  stats:
                    type: array
                    items:
                      type: object
                      properties:
                        label: { type: string }
                        value: { type: integer }
                        trend: { type: string }
                  alerts:
                    type: array
                    items:
                      type: object
                      properties:
                        level:
                          type: string
                          enum: [info, warning, critical]
                        message: { type: string }
                        time: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/storage:
    get:
      tags: [dashboard]
      operationId: getStorage
      x-required-scope: tenant:read
      summary: Storage usage for the dashboard
      responses:
        '200':
          description: Storage usage
          content:
            application/json:
              schema:
                type: object
                properties:
                  total_bytes: { type: integer, format: int64 }
                  alloc_bytes: { type: integer, format: int64 }
                  per_seat_bytes: { type: integer, format: int64 }
                  top_mailboxes:
                    type: array
                    items:
                      type: object
                      properties:
                        email: { type: string }
                        usage_bytes: { type: integer, format: int64 }
                  top_messages:
                    type: array
                    items:
                      type: object
                      properties:
                        sender: { type: string }
                        subject: { type: string }
                        size_bytes: { type: integer }
                        filenames:
                          type: array
                          items: { type: string }
                        queued_at: { type: string, format: date-time }
                  generated_at: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/domains/status:
    get:
      tags: [dashboard]
      operationId: getDomainsStatus
      x-required-scope: tenant:read
      summary: Domain health status for the dashboard
      responses:
        '200':
          description: Domain health status
          content:
            application/json:
              schema:
                type: object
                properties:
                  domains:
                    type: array
                    items:
                      type: object
                      properties:
                        domain: { type: string }
                        verified: { type: boolean }
                        checks:
                          type: array
                          items:
                            type: object
                            properties:
                              key: { type: string }
                              label: { type: string }
                              status:
                                type: string
                                enum: [healthy, warning, critical]
                  generated_at: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }

  /v1/health:
    get:
      tags: [dashboard]
      operationId: getTenantHealth
      x-required-scope: tenant:read
      summary: Full tenant health report
      responses:
        '200':
          description: Full tenant health report
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TenantHealthReport' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }


  /v1/migrations/credentials:
    post:
      tags: [migrations]
      operationId: createMigrationCredential
      x-required-scope: migrations:write
      summary: Store a migration credential
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [provider, credentials]
              properties:
                provider:
                  type: string
                  enum: [imap, google, microsoft, generic]
                label: { type: string }
                credentials:
                  type: object
                  required: [host, port]
                  properties:
                    host: { type: string }
                    port: { type: integer }
                    username: { type: string }
                    password: { type: string }
                    oauth_token: { type: string }
      responses:
        '201':
          description: Credential stored
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MigrationCredential'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }
    get:
      tags: [migrations]
      operationId: listMigrationCredentials
      x-required-scope: migrations:read
      summary: List migration credentials
      responses:
        '200':
          description: Credential list
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/MigrationCredential'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/credentials/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    delete:
      tags: [migrations]
      operationId: deleteMigrationCredential
      x-required-scope: migrations:write
      summary: Delete a migration credential
      responses:
        '204':
          description: Credential deleted
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations:
    post:
      tags: [migrations]
      operationId: createMigration
      x-required-scope: migrations:write
      summary: Create a migration
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, credential_id, source_provider]
              properties:
                name: { type: string }
                credential_id: { type: string, format: uuid }
                source_provider: { type: string }
                settings:
                  $ref: '#/components/schemas/MigrationSettings'
      responses:
        '201':
          description: Migration created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Migration'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }
    get:
      tags: [migrations]
      operationId: listMigrations
      x-required-scope: migrations:read
      summary: List migrations
      responses:
        '200':
          description: Migration list
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Migration'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [migrations]
      operationId: getMigration
      x-required-scope: migrations:read
      summary: Get a migration
      responses:
        '200':
          description: Migration details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Migration'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }
    patch:
      tags: [migrations]
      operationId: updateMigration
      x-required-scope: migrations:write
      summary: Update a migration
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                settings:
                  $ref: '#/components/schemas/MigrationSettings'
      responses:
        '200':
          description: Migration updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Migration'
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }
    delete:
      tags: [migrations]
      operationId: deleteMigration
      x-required-scope: migrations:write
      summary: Delete a migration
      responses:
        '204':
          description: Migration deleted
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Can only delete migrations in draft, completed, failed, or cancelled status.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/discover:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      tags: [migrations]
      operationId: discoverMigration
      x-required-scope: migrations:write
      summary: Discover source mailboxes
      responses:
        '202':
          description: Discovery started
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status: { type: string }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Migration is not in draft status.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/map:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      tags: [migrations]
      operationId: mapMigration
      x-required-scope: migrations:write
      summary: Map source to destination mailboxes
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [mappings]
              properties:
                mappings:
                  type: array
                  items:
                    type: object
                    required: [source_email, dest_email]
                    properties:
                      source_email: { type: string, format: email }
                      dest_email: { type: string, format: email }
      responses:
        '200':
          description: Mappings applied
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status: { type: string }
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/start:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      tags: [migrations]
      operationId: startMigration
      x-required-scope: migrations:write
      summary: Start the migration
      responses:
        '202':
          description: Migration started
          content:
            application/json:
              schema:
                type: object
                required: [status, mailboxes_queued]
                properties:
                  status: { type: string }
                  mailboxes_queued: { type: integer }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Migration is not in mapped or pilot_complete status.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/cancel:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      tags: [migrations]
      operationId: cancelMigration
      x-required-scope: migrations:write
      summary: Cancel a running migration
      responses:
        '200':
          description: Migration cancelled
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status: { type: string }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Cannot cancel migration from its current status.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/delta-sync:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      tags: [migrations]
      operationId: deltaSyncMigration
      x-required-scope: migrations:write
      summary: Run a delta sync
      responses:
        '202':
          description: Delta sync started
          content:
            application/json:
              schema:
                type: object
                required: [status, mailboxes_queued]
                properties:
                  status: { type: string }
                  mailboxes_queued: { type: integer }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Migration is not in staged status.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/final-sync:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      tags: [migrations]
      operationId: finalSyncMigration
      x-required-scope: migrations:write
      summary: Run the final sync before cutover
      responses:
        '202':
          description: Final sync started
          content:
            application/json:
              schema:
                type: object
                required: [status, mailboxes_queued]
                properties:
                  status: { type: string }
                  mailboxes_queued: { type: integer }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Migration is not in cutover_pending status.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/validate:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      tags: [migrations]
      operationId: validateMigration
      x-required-scope: migrations:write
      summary: Validate migrated data
      responses:
        '202':
          description: Validation started
          content:
            application/json:
              schema:
                type: object
                required: [status, mailboxes_queued]
                properties:
                  status: { type: string }
                  mailboxes_queued: { type: integer }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Migration is not in final_syncing status.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/retry:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      tags: [migrations]
      operationId: retryMigration
      x-required-scope: migrations:write
      summary: Retry a failed or cancelled migration
      responses:
        '200':
          description: Migration retried
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status: { type: string }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '409':
          description: Migration is not in failed or cancelled status.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/progress:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [migrations]
      operationId: getMigrationProgress
      x-required-scope: migrations:read
      summary: Get migration progress
      responses:
        '200':
          description: Migration progress
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MigrationProgress'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/mailboxes:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [migrations]
      operationId: listMigrationMailboxes
      x-required-scope: migrations:read
      summary: List migration mailboxes
      responses:
        '200':
          description: Migration mailbox list
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/MigrationMailbox'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/mailboxes/{mbxId}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
      - name: mbxId
        in: path
        required: true
        schema: { type: string, format: uuid }
    patch:
      tags: [migrations]
      operationId: updateMigrationMailbox
      x-required-scope: migrations:write
      summary: Update a migration mailbox
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                dest_email: { type: string }
                status:
                  type: string
                  description: Can only be set to "skipped".
      responses:
        '204':
          description: Mailbox updated
        '400': { $ref: '#/components/responses/ProblemBadRequest' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/events:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [migrations]
      operationId: listMigrationEvents
      x-required-scope: migrations:read
      summary: List migration events
      responses:
        '200':
          description: Migration event list
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/MigrationEvent'
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }

  /v1/migrations/{id}/dns-check:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [migrations]
      operationId: checkMigrationDNS
      x-required-scope: migrations:read
      summary: Check DNS readiness for cutover
      responses:
        '200':
          description: DNS readiness check results
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MigrationDNSCheck' }
        '400':
          description: The id is not a UUID, or the migration has no mapped destination mailboxes to check.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '401': { $ref: '#/components/responses/ProblemUnauthorized' }
        '403': { $ref: '#/components/responses/ProblemForbidden' }
        '404': { $ref: '#/components/responses/ProblemNotFound' }
        '503': { $ref: '#/components/responses/ProblemServiceUnavailable' }



components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: lk_live_<prefix>_<secret>
      description: API key, format `lk_live_<8-char-prefix>_<32-char-secret>`.
    oauth2:
      type: oauth2
      description: |
        OAuth 2.1 (authorization code + PKCE). The access token is sent as the
        `Authorization: Bearer` credential, exactly like an API key, so any SDK
        that accepts a bearer token works with OAuth. Discovery:
        `/.well-known/oauth-authorization-server`.
      flows:
        authorizationCode:
          authorizationUrl: https://api.lockally.com/oauth/authorize
          tokenUrl: https://api.lockally.com/oauth/token
          scopes:
            inboxes:read: Read agent-accessible mailboxes and threads
            inboxes:write: Send and act on agent-accessible mailboxes

  schemas:
    Attachment:
      type: object
      properties:
        name:   { type: string }
        type:   { type: string, description: MIME type. }
        size:   { type: integer, description: Bytes. }
        blobId: { type: string }
        partId: { type: string }

    InjectionRisk:
      type: object
      properties:
        flagged: { type: boolean }
        signals: { type: array, items: { type: string }, description: The phrases that tripped the check. }

    Annotations:
      type: object
      description: >
        Signals computed at ingest, before an agent sees the message. A key is
        absent when its check did not fire.
      properties:
        attachment_types: { type: array, items: { type: string } }
        meeting_request:  { type: boolean }
        injection_risk:   { $ref: '#/components/schemas/InjectionRisk' }

    PolicyFlags:
      type: object
      description: >
        Why a draft was held. A key is absent when that check passed. The set
        is closed: a flag added to the policy engine must be added here too,
        or typed clients will drop it.
      properties:
        always_approve:  { type: boolean }
        injection_risk:  { type: boolean }
        new_recipient:   { type: array, items: { type: string } }
        new_thread:      { type: boolean }
        pii:             { type: array, items: { type: string } }
        recipient_count: { type: integer }

    Classification:
      type: object
      properties:
        intent:           { type: string, description: 'For example support_request, sales_lead, billing, spam.' }
        urgency:          { type: string, enum: [low, normal, high] }
        summary:          { type: string, description: One line. }
        suggested_action: { type: string, description: One line. }

    # ── Agent and inbox surface ───────────────────────────────────────────
    # Written from internal/api/agent_read.go, agent_write.go,
    # agent_drafts_api.go, agent_contacts.go and ai.go. These responses were
    # typed `{type: object}` until 0.3.0, so no generated client could model
    # them. Field names and optionality follow the Go json tags exactly.

    Inbox:
      type: object
      required: [id, email, thread_count]
      properties:
        id:              { type: string, format: uuid }
        email:           { type: string, format: email }
        last_message_at: { type: string, format: date-time, nullable: true }
        thread_count:    { type: integer }

    InboxList:
      type: object
      required: [inboxes]
      properties:
        inboxes: { type: array, items: { $ref: '#/components/schemas/Inbox' } }

    ThreadSummary:
      type: object
      required: [id, participants, message_count]
      properties:
        id:              { type: string, format: uuid }
        subject:         { type: string, nullable: true }
        participants:    { type: array, items: { type: string, format: email } }
        message_count:   { type: integer }
        last_message_at: { type: string, format: date-time, nullable: true }
        last_direction:  { type: string, nullable: true, enum: [inbound, outbound, null] }

    ThreadList:
      type: object
      required: [mailbox, threads]
      properties:
        mailbox: { type: string, format: email }
        threads: { type: array, items: { $ref: '#/components/schemas/ThreadSummary' } }

    ThreadMessage:
      type: object
      required: [id, direction, rfc_message_id, from, to, has_attachments, received_at]
      properties:
        id:              { type: string, format: uuid }
        direction:       { type: string, enum: [inbound, outbound] }
        rfc_message_id:  { type: string, description: The Internet Message-ID, not the Lockally id. }
        in_reply_to:     { type: string }
        subject:         { type: string }
        from:            { type: string, format: email }
        to:              { type: array, items: { type: string, format: email } }
        snippet:         { type: string }
        has_attachments: { type: boolean }
        attachments:     { type: array, items: { $ref: '#/components/schemas/Attachment' } }
        annotations:     { $ref: '#/components/schemas/Annotations' }
        received_at:     { type: string, format: date-time }

    Thread:
      type: object
      required: [thread, mailbox, messages]
      properties:
        thread:   { $ref: '#/components/schemas/ThreadSummary' }
        mailbox:  { type: string, format: email }
        messages:
          type: array
          description: Chronological. Reading never marks a message read.
          items: { $ref: '#/components/schemas/ThreadMessage' }

    ThreadMessageBody:
      type: object
      required: [thread_id, mailbox, message]
      properties:
        thread_id: { type: string, format: uuid }
        mailbox:   { type: string, format: email }
        message:   { $ref: '#/components/schemas/ThreadMessage' }
        body:
          type: object
          description: Absent when the stored message could not be fetched.
          properties:
            text:      { type: string }
            html:      { type: string }
            truncated: { type: boolean }
        body_unavailable:
          type: string
          description: Present instead of body when the message could not be located in the mailbox.

    MarkReadResult:
      type: object
      properties:
        message_id: { type: string, format: uuid }
        read:       { type: boolean }

    AgentSendResult:
      type: object
      required: [id, message_id, status, thread_id]
      properties:
        id:         { type: string, format: uuid, description: The Lockally message id. }
        message_id: { type: string, description: The Internet Message-ID. }
        status:     { type: string }
        warning:    { type: string, description: Set when the send is accepted but worth noting, for example a large recipient count. }
        thread_id:  { type: string, format: uuid, description: The conversation the message joined. }

    Draft:
      type: object
      required: [id, mailbox_id, to, status, policy_flags, created_at, updated_at]
      properties:
        id:              { type: string, format: uuid }
        mailbox_id:      { type: string, format: uuid }
        mailbox:         { type: string, format: email }
        thread_id:       { type: string, format: uuid }
        to:              { type: array, items: { type: string, format: email } }
        cc:              { type: array, items: { type: string, format: email } }
        subject:         { type: string }
        body_text:       { type: string }
        status:          { type: string, enum: [pending_approval, sent, rejected, cancelled] }
        policy_flags:    { $ref: '#/components/schemas/PolicyFlags' }
        reviewed_at:     { type: string, format: date-time }
        sent_message_id: { type: string, format: uuid }
        created_at:      { type: string, format: date-time }
        updated_at:      { type: string, format: date-time }

    DraftList:
      type: object
      required: [drafts]
      properties:
        drafts: { type: array, items: { $ref: '#/components/schemas/Draft' } }

    DraftResult:
      type: object
      required: [draft_id, status, policy_flags]
      properties:
        draft_id:     { type: string, format: uuid }
        status:       { type: string, enum: [pending_approval, sent] }
        policy_flags: { $ref: '#/components/schemas/PolicyFlags' }
        thread_id:    { type: string, format: uuid }
        sent:         { $ref: '#/components/schemas/AgentSendResult' }

    ContactLookup:
      type: object
      required: [email, known, internal]
      properties:
        email:    { type: string, format: email }
        known:    { type: boolean }
        internal: { type: boolean, description: True when the address is one of the tenant's own mailboxes. }
        contact:
          type: object
          properties:
            name:         { type: string }
            company:      { type: string }
            department:   { type: string }
            role:         { type: string }
            contact_type: { type: string }
            notes:        { type: string }
        history:
          type: object
          description: Correspondence history, limited to the mailboxes this key is granted.
          properties:
            thread_count: { type: integer }
            first_seen:   { type: string, format: date-time }
            last_seen:    { type: string, format: date-time }

    MailboxGrant:
      type: object
      properties:
        api_key_id: { type: string, format: uuid }
        mailbox_id: { type: string, format: uuid }
        mailbox:    { type: string, format: email }
        created_at: { type: string, format: date-time }

    MailboxGrantList:
      type: object
      required: [grants]
      properties:
        grants: { type: array, items: { $ref: '#/components/schemas/MailboxGrant' } }

    AiConfig:
      type: object
      required: [mode, model]
      properties:
        mode:            { type: string, enum: [off, byok, units] }
        model:           { type: string }
        byok_key_hint:   { type: string }
        units_balance:   { type: integer }
        units_available: { type: boolean, description: True when a platform model key is configured. }

    AiConfigUpdate:
      type: object
      required: [mode, model]
      properties:
        mode:  { type: string, enum: [off, byok, units] }
        model: { type: string }

    ThreadClassification:
      type: object
      required: [thread_id]
      properties:
        thread_id:      { type: string, format: uuid }
        cached:         { type: boolean, description: True when a previous classification was reused. }
        billed:         { type: boolean, description: True when this call consumed an AI unit. }
        classification: { $ref: '#/components/schemas/Classification' }

    Whoami:
      type: object
      required: [tenant, scopes, auth]
      properties:
        tenant:
          type: object
          properties:
            slug: { type: string }
            name: { type: string, description: What the account calls itself. }
            plan: { type: string }
        scopes: { type: array, items: { type: string } }
        auth:   { type: string, enum: [api_key, session] }
        key:
          type: object
          description: Present only when auth is api_key.
          properties:
            id:    { type: string, format: uuid }
            label: { type: string }

    SimulatedInbound:
      type: object
      properties:
        simulated:      { type: boolean }
        indexed:        { type: boolean, description: True when the message was adopted into a thread. }
        thread_id:      { type: string, format: uuid }
        message_id:     { type: string, format: uuid }
        rfc_message_id: { type: string }
        annotations:    { $ref: '#/components/schemas/Annotations' }

    SendMessage:
      type: object
      required: [from, to]
      properties:
        from:        { type: string, format: email }
        to:          { type: array, items: { type: string, format: email }, minItems: 1 }
        cc:          { type: array, items: { type: string, format: email } }
        bcc:         { type: array, items: { type: string, format: email } }
        subject:     { type: string }
        text:        { type: string }
        html:        { type: string }
        headers:     { type: object, additionalProperties: { type: string } }
        reply_to:      { type: string, format: email, description: "Where replies go. Required when `from` has no mailbox behind it. The named form `Acme Support <a@b.com>` is also accepted." }
        reply_to_name: { type: string, description: "Display name shown on `Reply-To`. Ignored without `reply_to`." }
        unsubscribe: { type: boolean }
        template_id: { type: string, format: uuid }
        variables:   { type: object, additionalProperties: { type: string } }
        send_at:     { type: string, format: date-time }
        attachments:
          type: array
          items:
            type: object
            required: [filename, content_type, content_base64]
            properties:
              filename:       { type: string }
              content_type:   { type: string }
              content_base64: { type: string }
    TrackingPolicy:
      type: object
      required: [track_opens, track_clicks, configured]
      properties:
        track_opens:  { type: boolean }
        track_clicks: { type: boolean }
        updated_at:   { type: string, format: date-time, description: "Absent until a policy has been set." }
        configured:
          type: boolean
          description: "Whether this deployment holds a tracking signing secret. False means tracking cannot work whatever the flags say."

    BatchResult:
      type: object
      properties:
        index:      { type: integer }
        id:         { type: string, format: uuid }
        message_id: { type: string }
        status:     { type: string, enum: [queued, scheduled, suppressed, delivered], description: "\"suppressed\" means every recipient of that slot was on your suppression list, and it carries no id or message_id. \"delivered\" only appears on a test key: the send was simulated, not transmitted." }
        error:      { type: string, description: "Present when this message failed; the others are then absent." }
        warning:    { type: string, description: "Advisory, and NOT a failure. Today the only one is a template variable the template referenced and the request never supplied, which rendered as the empty string." }
    Template:
      type: object
      properties:
        id:         { type: string, format: uuid }
        name:       { type: string }
        subject:    { type: string }
        html:       { type: string }
        text:       { type: string }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
    TemplateInput:
      type: object
      required: [name]
      properties:
        name:    { type: string, description: "Template name (1–120 chars)." }
        subject: { type: string, description: "May contain {{variable}} placeholders." }
        html:    { type: string, description: "HTML body; {{variable}} values are HTML-escaped." }
        text:    { type: string, description: "Plain-text body." }
    Suppression:
      type: object
      properties:
        email:      { type: string, format: email }
        reason:     { type: string, enum: [unsubscribe, complaint, bounce, manual] }
        source:     { type: string }
        created_at: { type: string, format: date-time }
    MessageStats:
      type: object
      properties:
        window:
          type: object
          properties:
            from: { type: string, format: date-time }
            to:   { type: string, format: date-time }
        domain: { type: string }
        sent:   { type: integer }
        counts:
          type: object
          properties:
            delivered: { type: integer }
            bounced:   { type: integer }
            deferred:  { type: integer }
            complaint: { type: integer }
        rates:
          type: object
          properties:
            delivered: { type: number, format: float }
            bounced:   { type: number, format: float }
            deferred:  { type: number, format: float }
            complaint: { type: number, format: float }
    Tenant:
      type: object
      required: [id, slug, display_name, status, plan, rate_cap_per_min, daily_msg_quota, admin_email, created_at]
      properties:
        id:                 { type: string, format: uuid }
        slug:               { type: string, example: workgrid }
        display_name:       { type: string, example: WorkGrid }
        status:
          type: string
          enum: [active, suspended, closing, closed]
        plan:               { type: string, example: starter }
        rate_cap_per_min:   { type: integer, description: "Per-tenant share of the per-VPS 5/min outbound cap (L6).", example: 1 }
        daily_msg_quota:    { type: integer, example: 1000 }
        admin_email:        { type: string, format: email }
        created_at:         { type: string, format: date-time }
        suspended_at:       { type: string, format: date-time, nullable: true }
        closed_at:          { type: string, format: date-time, nullable: true }
        hard_delete_after:  { type: string, format: date-time, nullable: true }

    Domain:
      type: object
      required: [id, tenant_id, domain, verification_token, verified, dkim_selector, dkim_public_record, created_at]
      properties:
        id:                 { type: string, format: uuid }
        tenant_id:          { type: string, format: uuid }
        domain:             { type: string, format: hostname, example: acme.com }
        verification_token: { type: string, example: "lkv-zyj4p5qbv6i4rjm7s3wrrkr3jzo3lrvy" }
        verified:           { type: boolean }
        verified_at:        { type: string, format: date-time, nullable: true }
        dkim_selector:      { type: string, example: lockally }
        dkim_public_record: { type: string, example: "v=DKIM1; k=rsa; p=MIIBIjAN..." }
        created_at:         { type: string, format: date-time }
        records:
          type: array
          description: DNS records the tenant must publish under their own DNS.
          items: { $ref: '#/components/schemas/DNSRecord' }

    DNSRecord:
      type: object
      required: [type, name, value, ttl, purpose]
      properties:
        type:     { type: string, enum: [TXT, MX] }
        name:     { type: string, format: hostname }
        value:    { type: string }
        ttl:      { type: integer, example: 300 }
        priority: { type: integer, description: "MX records only.", nullable: true }
        purpose:
          type: string
          enum: [verification, spf, dkim, mx-primary, mx-backup, dmarc]

    Admin:
      type: object
      required: [id, tenant_id, email, role, created_at]
      properties:
        id:            { type: string, format: uuid }
        tenant_id:     { type: string, format: uuid }
        email:         { type: string, format: email }
        display_name:  { type: string }
        role:          { type: string, enum: [admin, viewer] }
        last_login_at: { type: string, format: date-time, nullable: true }
        created_at:    { type: string, format: date-time }

    AdminFull:
      allOf:
        - $ref: '#/components/schemas/Admin'
        - type: object
          required: [disabled]
          properties:
            disabled:    { type: boolean }
            disabled_at: { type: string, format: date-time, nullable: true }
            password:
              type: string
              description: "Present ONLY on POST response when lockally generated the password. Shown once."

    Webhook:
      type: object
      required: [id, tenant_id, url, events, paused, consecutive_failures, created_at]
      properties:
        id:                   { type: string, format: uuid }
        tenant_id:            { type: string, format: uuid }
        url:                  { type: string, format: uri }
        events:               { type: array, items: { type: string } }
        paused:               { type: boolean }
        paused_at:            { type: string, format: date-time, nullable: true }
        last_success_at:      { type: string, format: date-time, nullable: true }
        last_failure_at:      { type: string, format: date-time, nullable: true }
        consecutive_failures: { type: integer }
        created_at:           { type: string, format: date-time }
        signing_secret:
          type: string
          description: "Hex-encoded HMAC-SHA256 key. Present ONLY on POST response."

    Mailbox:
      type: object
      required: [id, tenant_id, domain_id, email, quota_bytes, disabled, created_at]
      properties:
        id:                 { type: string, format: uuid }
        tenant_id:          { type: string, format: uuid }
        domain_id:          { type: string, format: uuid }
        email:              { type: string, format: email }
        quota_bytes:        { type: integer, format: int64 }
        disabled:           { type: boolean }
        disabled_at:        { type: string, format: date-time, nullable: true }
        soft_deleted_at:    { type: string, format: date-time, nullable: true }
        hard_delete_after:  { type: string, format: date-time, nullable: true }
        created_at:         { type: string, format: date-time }
        password:
          type: string
          description: "ONLY present on POST response when lockally generated the password. Shown once."

    ReturnPath:
      type: object
      required: [status, host, records]
      properties:
        status:       { type: string, enum: [off, pending, active] }
        host:         { type: string, example: bounces.acme.com }
        records:
          type: array
          items: { $ref: '#/components/schemas/DNSRecord' }
        check:
          type: object
          description: Present after a verify call.
          properties:
            mx:  { type: boolean }
            spf: { type: boolean }
        requested_at: { type: string, format: date-time }
        verified_at:  { type: string, format: date-time }

    Alias:
      type: object
      required: [id, tenant_id, alias_address, alias_target, created_at]
      properties:
        id:            { type: string, format: uuid }
        tenant_id:     { type: string, format: uuid }
        alias_address: { type: string, format: email }
        alias_target:  { type: string, format: email }
        created_at:    { type: string, format: date-time }

    APIKey:
      type: object
      required: [id, tenant_id, prefix, scopes, label, created_at]
      properties:
        id:            { type: string, format: uuid }
        tenant_id:     { type: string, format: uuid }
        prefix:        { type: string, description: "8-char public prefix; safe to store and display.", example: fbl73bhj }
        scopes:        { type: array, items: { type: string } }
        label:         { type: string, example: ci-pipeline }
        last_used_at:  { type: string, format: date-time, nullable: true }
        revoked_at:    { type: string, format: date-time, nullable: true }
        created_at:    { type: string, format: date-time }
        test:
          type: boolean
          description: "True for an lk_test_* key: the whole request path runs but a send never reaches the mail server and nothing counts against the account."
        expires_at:
          type: string
          format: date-time
          nullable: true
          description: |
            When the key stops authenticating. Null means it does not expire,
            which is how every key behaved before expiry existed. Enforced at
            authentication, so the key fails the first request after this
            moment rather than whenever a sweep runs.
        rotated_to:
          type: string
          format: uuid
          nullable: true
          description: |
            The successor issued by `POST /v1/api-keys/{id}/rotate`. Set on the
            PREDECESSOR, so you can see which key replaced this one while both
            still work through the overlap window.

    Message:
      type: object
      required: [id, tenant_id, message_id, sender, recipients, status, queued_at, updated_at]
      properties:
        id:             { type: string, format: uuid }
        tenant_id:      { type: string, format: uuid }
        message_id:     { type: string, description: "RFC 5322 Message-ID header, including angle brackets." }
        sender:         { type: string, format: email }
        recipients:     { type: array, items: { type: string, format: email } }
        subject:        { type: string, nullable: true }
        status:         { type: string, enum: [queued, sending, delivered, bounced, deferred, complaint] }
        queued_at:      { type: string, format: date-time }
        updated_at:     { type: string, format: date-time }
        bounce_reason:  { type: string, nullable: true }
        size_bytes:     { type: integer, nullable: true }
        metadata:
          type: object
          additionalProperties: { type: string }
          description: "The sender's own key/value from the send request. Always present; `{}` when none was set."
        tags:
          type: array
          items: { type: string }
          description: "Grouping labels, lowercased and deduplicated. Always present; `[]` when none were set."

    MessageDetail:
      description: >
        A single message with the content captured at send time. Returned only by
        GET /v1/messages/{id} (the list stays summary-only). Attachments are not returned.
      allOf:
        - $ref: '#/components/schemas/Message'
        - type: object
          properties:
            from:    { type: string, format: email }
            to:      { type: array, items: { type: string, format: email } }
            cc:      { type: array, items: { type: string, format: email } }
            bcc:     { type: array, items: { type: string, format: email } }
            text:    { type: string }
            html:    { type: string }
            headers: { type: object, additionalProperties: { type: string } }

    User:
      type: object
      required: [id, tenant_id, email, first_name, last_name, status, created_at, updated_at]
      properties:
        id:             { type: string, format: uuid }
        tenant_id:      { type: string, format: uuid }
        email:          { type: string, format: email }
        first_name:     { type: string }
        last_name:      { type: string }
        title:          { type: string }
        department:     { type: string }
        status:
          type: string
          enum: [active, suspended, deprovisioned]
        created_at:     { type: string, format: date-time }
        updated_at:     { type: string, format: date-time }
        mailbox_count:  { type: integer }

    BillingStatus:
      type: object
      required:
        - plan
        - display_name
        - mode
        - rate_cap_per_min
        - monthly_included_sends
        - msgs_this_period
        - status
        - price_naira_per_seat
        - created_at
        - send_units_balance
        - unit_bundles
        - catalog
      properties:
        plan:                    { type: string }
        display_name:            { type: string }
        mode:
          type: string
          enum: [api, business, both]
        rate_cap_per_min:        { type: integer }
        monthly_included_sends:  { type: integer }
        msgs_this_period:        { type: integer }
        status:
          type: string
          enum: [active, suspended]
        price_naira_per_seat:    { type: integer }
        subscribed_at:           { type: string, format: date-time, nullable: true }
        current_period_end:      { type: string, format: date-time, nullable: true }
        created_at:              { type: string, format: date-time }
        send_units_balance:      { type: integer }
        send_units_next_expiry:  { type: string, format: date-time, nullable: true }
        unit_bundles:
          type: array
          items: { $ref: '#/components/schemas/UnitBundle' }
        catalog:
          type: array
          items: { $ref: '#/components/schemas/PlanCatalogEntry' }

    UnitBundle:
      type: object
      required: [key, units, display_name, price_naira, display_price]
      properties:
        key:           { type: string }
        units:         { type: integer }
        display_name:  { type: string }
        price_naira:   { type: integer }
        display_price: { type: string }

    PlanCatalogEntry:
      type: object
      required:
        - name
        - display_name
        - description
        - price_naira_per_seat
        - rate_cap_per_min
        - monthly_included_sends
        - has_shared_mailboxes
        - has_send_units
        - has_ai_units
        - has_e2e_encryption
      properties:
        name:                  { type: string }
        display_name:          { type: string }
        description:           { type: string }
        price_naira_per_seat:  { type: integer }
        rate_cap_per_min:      { type: integer }
        monthly_included_sends: { type: integer }
        has_shared_mailboxes:  { type: boolean }
        has_send_units:        { type: boolean }
        has_ai_units:          { type: boolean }
        has_e2e_encryption:    { type: boolean }

    AddOn:
      type: object
      required: [name, display_name, description, price_naira, pricing_model, active]
      properties:
        name:          { type: string }
        display_name:  { type: string }
        description:   { type: string }
        price_naira:   { type: integer }
        pricing_model: { type: string }
        active:        { type: boolean }

    SharedMember:
      type: object
      required: [id, mailbox_id, tenant_id, member_email, role, created_at]
      properties:
        id:           { type: string, format: uuid }
        mailbox_id:   { type: string, format: uuid }
        tenant_id:    { type: string, format: uuid }
        member_email: { type: string, format: email }
        role:
          type: string
          enum: [manager, member]
        created_at:   { type: string, format: date-time }

    DistributionListSummary:
      type: object
      required: [id, tenant_id, list_address, created_at, member_count]
      properties:
        id:           { type: string, format: uuid }
        tenant_id:    { type: string, format: uuid }
        list_address: { type: string, format: email }
        name:         { type: string, nullable: true }
        created_at:   { type: string, format: date-time }
        member_count: { type: integer }

    DistributionListDetail:
      type: object
      required: [id, tenant_id, list_address, created_at, members, member_count]
      properties:
        id:           { type: string, format: uuid }
        tenant_id:    { type: string, format: uuid }
        list_address: { type: string, format: email }
        name:         { type: string, nullable: true }
        created_at:   { type: string, format: date-time }
        members:
          type: array
          items: { type: string }
        member_count: { type: integer }

    DedicatedIPRequest:
      type: object
      required: [id, tenant_id, status, created_at]
      properties:
        id:          { type: string, format: uuid }
        tenant_id:   { type: string, format: uuid }
        status:
          type: string
          enum: [pending, approved, rejected]
        note:        { type: string, nullable: true }
        admin_note:  { type: string, nullable: true }
        created_at:  { type: string, format: date-time }
        resolved_at: { type: string, format: date-time, nullable: true }


    Calendar:
      type: object
      required: [id, tenant_id, name, visibility, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        tenant_id: { type: string, format: uuid }
        name: { type: string }
        color: { type: string }
        owner_email: { type: string }
        description: { type: string }
        calendar_type:
          type: string
          description: |
            What the calendar is for. Separate from visibility, which is who may
            see it: a team calendar can be open to everyone and a department one
            restricted to named people. "personal" is a person's own and is not
            listed in the console's management table.
          enum: [personal, organization, department, team, shared]
        owner_unit:
          type: string
          description: The owning department or office. Empty on a personal calendar, which is owned by owner_email.
        visibility:
          type: string
          enum: [private, tenant, department]
        access_department:
          type: string
          description: |
            Which department may see it, when visibility is "department". Matched
            against the department recorded on a user, so access follows a person
            between departments with no membership list to maintain.
        status:
          type: string
          description: Archived keeps the calendar, its events and its feed, and stops it taking new events.
          enum: [active, archived]
        feed_url: { type: string, format: uri }
        event_count: { type: integer }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    CalendarEvent:
      type: object
      required: [id, calendar_id, tenant_id, uid, title, starts_at, ends_at, all_day, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        calendar_id: { type: string, format: uuid }
        tenant_id: { type: string, format: uuid }
        uid: { type: string }
        title: { type: string }
        description: { type: string }
        location: { type: string }
        starts_at: { type: string, format: date-time }
        ends_at: { type: string, format: date-time }
        all_day: { type: boolean }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    CalendarMember:
      type: object
      required: [id, calendar_id, tenant_id, user_email, role, created_at]
      properties:
        id: { type: string, format: uuid }
        calendar_id: { type: string, format: uuid }
        tenant_id: { type: string, format: uuid }
        user_email: { type: string, format: email }
        role:
          type: string
          enum: [viewer, editor, owner]
        created_at: { type: string, format: date-time }

    CalendarPolicies:
      type: object
      required: [tenant_id]
      properties:
        tenant_id: { type: string, format: uuid }
        max_meeting_duration_mins: { type: integer }
        working_hours_start: { type: string }
        working_hours_end: { type: string }
        booking_window_days: { type: integer }
        recurring_meeting_limit: { type: integer }
        resource_approval_mode:
          type: string
          enum: [auto_approve, require_approval, restricted]
        external_invites_allowed: { type: boolean }
        external_sharing_allowed: { type: boolean }
        public_links_enabled: { type: boolean }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    CalendarIntegration:
      type: object
      required: [id, tenant_id, provider, status, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        tenant_id: { type: string, format: uuid }
        provider:
          type: string
          enum: [exchange, google_calendar, teams, zoom, erp]
        label: { type: string }
        status:
          type: string
          enum: [connected, disconnected, error, syncing]
        last_sync_at: { type: string, format: date-time, nullable: true }
        error_message: { type: string, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    Resource:
      type: object
      required: [id, tenant_id, name, type, status, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        tenant_id: { type: string, format: uuid }
        name: { type: string }
        type:
          type: string
          enum: [meeting_room, equipment]
        capacity: { type: integer, nullable: true }
        status: { type: string }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }


    Contact:
      type: object
      required: [id, tenant_id, name, email, contact_type, status, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        tenant_id: { type: string, format: uuid }
        name: { type: string }
        email: { type: string, format: email }
        phone: { type: string }
        company: { type: string }
        notes: { type: string }
        contact_type:
          type: string
          enum: [internal, external]
        source: { type: string }
        department: { type: string }
        role: { type: string }
        status: { type: string }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        external_system:
          type: string
          description: The system that owns this contact's external id. Absent on contacts made by hand.
        external_id:
          type: string
          description: The contact's id in `external_system`. Absent on contacts made by hand.

    ExternalContactInput:
      type: object
      required: [email]
      properties:
        email: { type: string, format: email }
        name:
          type: string
          description: Defaults to the email address when empty.
        phone: { type: string }
        company: { type: string }
        notes: { type: string }
        contact_type:
          type: string
          enum: [internal, external]
          default: external
        department: { type: string }
        role: { type: string }
        status:
          type: string
          enum: [active, disabled]
          default: active

    ContactList:
      type: object
      required: [id, tenant_id, name, visibility, member_count, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        tenant_id: { type: string, format: uuid }
        name: { type: string }
        description: { type: string }
        visibility:
          type: string
          enum: [company_wide, restricted]
        member_count: { type: integer }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    GALSettings:
      type: object
      required: [tenant_id, gal_enabled, hide_from_directory, department_grouping, search_visibility, include_external_contacts]
      properties:
        tenant_id: { type: string, format: uuid }
        gal_enabled: { type: boolean }
        hide_from_directory: { type: boolean }
        department_grouping: { type: boolean }
        search_visibility:
          type: string
          enum: [all_users, same_department, admins_only]
        include_external_contacts: { type: boolean }
        last_index_rebuilt_at: { type: string, format: date-time, nullable: true }
        last_synced_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    DirectoryPermissions:
      type: object
      required: [tenant_id, contact_view_access, contact_edit_access, list_manage_access, external_sharing]
      properties:
        tenant_id: { type: string, format: uuid }
        contact_view_access:
          type: string
          enum: [all_users, same_department, admins_only]
        contact_edit_access:
          type: string
          enum: [all_users, admins_only]
        list_manage_access:
          type: string
          enum: [all_users, list_owners, admins_only]
        external_sharing:
          type: string
          enum: [allowed, restricted, disabled]
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    UserEvent:
      type: object
      properties:
        email: { type: string }
        event_at: { type: string, format: date-time }
        days_inactive: { type: integer, nullable: true }

    AuditEvent:
      type: object
      properties:
        email: { type: string }
        event_type: { type: string }
        detail: { type: string, nullable: true }
        ip: { type: string, nullable: true }
        time: { type: string, format: date-time }


    MigrationCredential:
      type: object
      required: [id, tenant_id, provider, created_at, updated_at]
      properties:
        id:                { type: string, format: uuid }
        tenant_id:         { type: string, format: uuid }
        provider:
          type: string
          enum: [imap, google, microsoft, generic]
        encryption_key_id: { type: string }
        label:             { type: string, nullable: true }
        created_at:        { type: string, format: date-time }
        updated_at:        { type: string, format: date-time }

    Migration:
      type: object
      required: [id, tenant_id, credential_id, name, status, source_provider, mailbox_count, created_at, updated_at]
      properties:
        id:              { type: string, format: uuid }
        tenant_id:       { type: string, format: uuid }
        credential_id:   { type: string, format: uuid }
        name:            { type: string }
        status:
          type: string
          enum:
            - draft
            - discovering
            - discovered
            - mapped
            - pilot_running
            - pilot_complete
            - running
            - staged
            - cutover_pending
            - final_syncing
            - validating
            - completed
            - failed
            - cancelled
        source_provider: { type: string }
        source_summary:  { type: string, nullable: true }
        settings:
          $ref: '#/components/schemas/MigrationSettings'
        error_message:   { type: string, nullable: true }
        started_at:      { type: string, format: date-time, nullable: true }
        completed_at:    { type: string, format: date-time, nullable: true }
        mailbox_count:   { type: integer }
        created_at:      { type: string, format: date-time }
        updated_at:      { type: string, format: date-time }

    MigrationSettings:
      type: object
      properties:
        max_concurrent_mailboxes: { type: integer }
        max_concurrent_messages:  { type: integer }
        source_rate_limit:        { type: integer }
        batch_size:               { type: integer }
        skip_folders:
          type: array
          items: { type: string }

    MigrationProgress:
      type: object
      required: [migration_id, status, total_mailboxes, completed_mailboxes, failed_mailboxes, total_messages, synced_messages, failed_messages, percent_complete, mailboxes]
      properties:
        migration_id:        { type: string, format: uuid }
        status:              { type: string }
        total_mailboxes:     { type: integer }
        completed_mailboxes: { type: integer }
        failed_mailboxes:    { type: integer }
        total_messages:      { type: integer }
        synced_messages:     { type: integer }
        failed_messages:     { type: integer }
        percent_complete:    { type: number }
        mailboxes:
          type: array
          items:
            type: object
            required: [source_email, status, synced_message_count, failed_message_count, percent_complete]
            properties:
              source_email:        { type: string }
              dest_email:          { type: string, nullable: true }
              status:              { type: string }
              source_message_count: { type: integer, nullable: true }
              synced_message_count: { type: integer }
              failed_message_count: { type: integer }
              percent_complete:    { type: number }

    MigrationMailbox:
      type: object
      required: [id, migration_id, tenant_id, source_email, status, synced_message_count, failed_message_count, created_at, updated_at]
      properties:
        id:                  { type: string, format: uuid }
        migration_id:        { type: string, format: uuid }
        tenant_id:           { type: string, format: uuid }
        source_email:        { type: string }
        dest_email:          { type: string, nullable: true }
        dest_mailbox_id:     { type: string, format: uuid, nullable: true }
        status:              { type: string }
        source_message_count: { type: integer, nullable: true }
        synced_message_count: { type: integer }
        failed_message_count: { type: integer }
        source_size_bytes:   { type: integer, format: int64 }
        synced_size_bytes:   { type: integer, format: int64 }
        last_synced_uid:     { type: string, nullable: true }
        last_synced_at:      { type: string, format: date-time, nullable: true }
        error_message:       { type: string, nullable: true }
        started_at:          { type: string, format: date-time, nullable: true }
        completed_at:        { type: string, format: date-time, nullable: true }
        created_at:          { type: string, format: date-time }
        updated_at:          { type: string, format: date-time }

    TenantHealthReport:
      type: object
      description: The workspace health snapshot behind the console dashboard. DNS checks are live lookups, so a domain whose DNS cannot be read shows as a warning rather than an error.
      required: [overall_score, checks, generated_at]
      properties:
        overall_score: { type: integer, minimum: 0, maximum: 100 }
        checks:
          type: array
          items: { $ref: '#/components/schemas/TenantHealthCheck' }
        generated_at: { type: string, format: date-time }
    TenantHealthCheck:
      type: object
      required: [key, label, status, detail]
      properties:
        key:
          type: string
          description: Stable identifier, today one of `domain_verification`, `smtp`, `storage`, `security`. Treat unknown keys as new checks, not errors.
        label: { type: string, description: Human-readable name for display. }
        status:
          type: string
          description: '`healthy`, `warning` or `critical`.'
        detail: { type: string }
    MigrationDNSCheck:
      type: object
      description: Live DNS readiness of the destination domains, for deciding when to cut over. `ready` is true only when every domain's MX points at Lockally and its SPF authorises it.
      required: [ready, domains]
      properties:
        ready: { type: boolean }
        domains:
          type: array
          items: { $ref: '#/components/schemas/MigrationDomainDNS' }
    MigrationDomainDNS:
      type: object
      description: Each record is `healthy`, `warning` or `critical`, or empty when it could not be checked.
      required: [domain, mx, spf, dkim, dmarc]
      properties:
        domain: { type: string }
        mx: { type: string }
        spf: { type: string }
        dkim: { type: string }
        dmarc: { type: string }
    MigrationEvent:
      type: object
      required: [id, migration_id, tenant_id, event_type, actor, created_at]
      properties:
        id:            { type: string, format: uuid }
        migration_id:  { type: string, format: uuid }
        tenant_id:     { type: string, format: uuid }
        mailbox_id:    { type: string, format: uuid, nullable: true }
        event_type:    { type: string }
        actor:         { type: string }
        old_status:    { type: string, nullable: true }
        new_status:    { type: string, nullable: true }
        detail:        { type: string, nullable: true }
        created_at:    { type: string, format: date-time }


    Problem:
      description: RFC 9457 problem-details document.
      type: object
      required: [type, status, title]
      properties:
        type:     { type: string, format: uri, default: "about:blank" }
        status:   { type: integer }
        title:    { type: string }
        detail:   { type: string }
        instance: { type: string, format: uri }

  responses:
    ProblemBadRequest:
      description: Malformed request.
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
    ProblemUnauthorized:
      description: Missing, malformed, or invalid API key.
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
    ProblemForbidden:
      description: API key lacks the required scope.
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
    ProblemNotFound:
      description: Resource not found under the calling tenant.
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
    ProblemServiceUnavailable:
      description: Service is temporarily unable to handle the request (e.g. database unreachable).
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
