openapi: 3.0.3
info:
  title: JsonFabrica Platform — External API (via Gateway)
  version: "1.0.0"
  description: >
    Public entry point for the JsonFabrica JSON-generation platform. All `/v1/*`
    routes require an API key sent as `Authorization: Bearer <api-key>`. The
    gateway resolves the key to a tenant/role via svc-auth and forwards the
    request to the appropriate internal microservice, injecting trusted
    `X-Tenant-Id`/`X-Role` headers downstream (callers never set those
    themselves). `/health` is unauthenticated.


    **Request-path validation.** The gateway validates and normalizes every
    proxied `/v1/*` request path before forwarding it. Requests with malformed
    or out-of-scope paths are rejected with `400 VALIDATION_ERROR`. Dots
    *inside* a path segment (e.g. `person.firstName`) are fully supported.


    **Request correlation (`x-request-id`).** Every response — success or
    error, on every route including `/health` — carries an `x-request-id`
    header. Send your own `x-request-id` request header to have it honoured
    and echoed back, or omit it and the gateway generates a UUID. The same id
    is propagated to every internal service handling the request, so quoting
    it in a support request lets it be traced end to end. It is a correlation
    aid only: nothing is authenticated or authorized based on it.
  license:
    name: Proprietary
servers:
  - url: https://api.jsonfabrica.com
    description: Production
  - url: http://localhost:4000
    description: Local gateway (self-hosted)

security:
  - bearerAuth: []

tags:
  - name: Health
    description: Liveness check (no auth)
  - name: Auth
    description: Caller identity introspection
  - name: Templates
    description: Template CRUD and document generation
  - name: Sequences
    description: Per-tenant monotonic sequence generators
  - name: Batches
    description: Bulk/related document generation jobs
  - name: Admin
    description: Admin-only configuration (requires role=admin)
  - name: Usage
    description: Tenant usage/billing counters
  - name: Billing
    description: >
      Public, unauthenticated billing endpoints: self-serve signup (proxied
      to svc-auth, which itself calls svc-billing internally to create the
      Stripe customer/subscription) and the Stripe webhook ingestion
      passthrough. svc-billing's other routes are internal-only (see
      `api-docs/openapi-internal-services.yaml`).

paths:
  /health:
    get:
      tags: [Health]
      summary: Liveness check
      description: Returns service health. No authentication required.
      security: []
      responses:
        "200":
          description: Service is healthy
          content:
            application/json:
              schema:
                type: object
                properties:
                  status: { type: string, example: ok }
                  service: { type: string, example: svc-gateway }
              example:
                status: ok
                service: svc-gateway

  /v1/signup:
    post:
      tags: [Billing]
      summary: Self-serve tenant signup (starts an async, Stripe Checkout-based flow)
      description: >
        Public, unauthenticated. Proxied straight through to svc-auth's
        `POST /v1/signup`, which validates the request and rejects
        disposable email domains and the `enterprise` tier (manual sales
        only), then calls svc-billing internally to create a Stripe
        Checkout Session (`mode: subscription`) and returns a `checkoutUrl`
        to redirect the browser to. **No API key is returned by this call**
        — payment (including any SCA/3DS challenge) happens entirely on
        Stripe's hosted Checkout page. Every self-serve tier (`starter`,
        `growth`, `business`) starts with a 30-day free trial; a valid
        payment card is still required upfront (collected by Stripe), and
        it is charged automatically once the trial ends. Once payment
        clears, Stripe redirects the browser to the configured
        `SIGNUP_SUCCESS_URL` with `?session_id={CHECKOUT_SESSION_ID}` — poll
        `GET /v1/signup/session/{sessionId}` there to retrieve the issued
        API key (also emailed to the signup address as the durable/primary
        channel). Only available when the gateway is booted with
        `AUTH_SERVICE_URL` set (it is, in `docker-compose.product.yml`).
      security: []
      operationId: signup
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, tier]
              properties:
                email: { type: string, format: email }
                tier: { type: string, enum: [starter, growth, business] }
            example:
              email: owner@acme.example
              tier: starter
      responses:
        "201":
          description: Signup accepted — redirect the browser to `checkoutUrl` (or the signup was blocked — see `status`)
          content:
            application/json:
              schema:
                type: object
                properties:
                  tenantId: { type: string }
                  tier: { type: string }
                  status: { type: string, enum: [pending_payment, blocked] }
                  checkoutUrl:
                    type: string
                    nullable: true
                    description: Present when status is `pending_payment` — redirect the browser here to complete payment/SCA.
                  blockReason: { type: string, nullable: true }
              example:
                tenantId: tenant_a1b2c3
                tier: starter
                status: pending_payment
                checkoutUrl: https://checkout.stripe.com/c/pay/cs_test_a1b2c3
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          description: Rejected (disposable email domain, or enterprise tier requested)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorEnvelope" }

  /v1/signup/session/{sessionId}:
    get:
      tags: [Billing]
      summary: Poll a Checkout Session's fulfillment status (signup success page)
      description: >
        Public, unauthenticated — the Stripe Checkout Session id itself is
        the capability token (long, Stripe-generated, random, single-
        purpose). Proxied straight through to svc-auth's
        `GET /v1/signup/session/{sessionId}`, which proxies to svc-billing.
        Intended to be polled by the page at `SIGNUP_SUCCESS_URL` (~every
        2s while `pending`) after Stripe redirects the browser back with
        `?session_id={CHECKOUT_SESSION_ID}`. The returned `apiKey` is a
        **one-time read**: the first successful fetch after fulfillment
        returns the real key and clears it server-side; any subsequent
        fetch for the same session returns `apiKey: null` (email is the
        durable/primary channel regardless of whether the browser ever
        polls this endpoint). Only available when the gateway is booted
        with `AUTH_SERVICE_URL` set.
      security: []
      operationId: signupSessionStatus
      parameters:
        - name: sessionId
          in: path
          required: true
          schema: { type: string }
          example: cs_test_a1b2c3
      responses:
        "200":
          description: Session status (see `status` for which fields are populated)
          content:
            application/json:
              schema:
                type: object
                properties:
                  status: { type: string, enum: [pending, fulfilled, failed] }
                  tenantId: { type: string, description: "Present when status is fulfilled" }
                  tier: { type: string, description: "Present when status is fulfilled" }
                  apiKey:
                    type: string
                    nullable: true
                    description: Present when status is fulfilled; null once already consumed by an earlier fetch.
                  reason: { type: string, description: "Present when status is failed" }
              examples:
                pending:
                  value: { status: pending }
                fulfilledFirstFetch:
                  value: { status: fulfilled, tenantId: tenant_a1b2c3, tier: starter, apiKey: sk_live_EXAMPLE_not_a_real_key }
                fulfilledAlreadyConsumed:
                  value: { status: fulfilled, tenantId: tenant_a1b2c3, tier: starter, apiKey: null }
                failed:
                  value: { status: failed, reason: checkout.session.expired }
        "404":
          description: Unknown/garbage session id

  /v1/webhooks/stripe:
    post:
      tags: [Billing]
      summary: Stripe webhook ingestion (raw passthrough to svc-billing)
      description: >
        Public, unauthenticated (Stripe itself is the only expected caller;
        authenticity is established via `Stripe-Signature`, not an API
        key). The gateway forwards the request body byte-for-byte
        (unparsed) and the `Stripe-Signature` header to svc-billing —
        required for signature verification. Only available when the
        gateway is booted with `BILLING_SERVICE_URL` set. [VERIFY: full set
        of handled Stripe event types — see
        packages/svc-billing/src/webhookHandler.ts.]
      security: []
      operationId: stripeWebhook
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: Raw Stripe event payload.
      responses:
        "200":
          description: Event processed (or already-processed, deduped)
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  deduped: { type: boolean }
        "400":
          description: Invalid/missing Stripe signature
        "502":
          description: svc-billing unreachable

  /v1/billing/portal:
    post:
      tags: [Billing]
      summary: Get a Stripe Billing Portal link for the caller's own tenant
      description: >
        Requires `Authorization: Bearer <api-key>`. Mounted the same way as
        `POST /v1/signup` — proxied straight to svc-auth, which resolves the
        caller's own tenantId from the API key server-side (never accepted
        from the request body/path) and calls svc-billing internally to
        create a one-time Stripe Billing Portal session for that tenant.
        Open the returned `url` to let the tenant manage payment methods,
        view invoices, or cancel their subscription themselves
        (design/self-service-cancellation.md).
      operationId: billingPortal
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                returnUrl:
                  type: string
                  description: >
                    Where Stripe sends the tenant back after closing the
                    portal. Defaults to the jsonfabrica.com homepage when
                    omitted.
            example:
              returnUrl: https://jsonfabrica.com/
      responses:
        "200":
          description: Billing Portal session created
          content:
            application/json:
              schema:
                type: object
                properties:
                  url: { type: string }
                example:
                  url: https://billing.stripe.com/session/test_abc123
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: No billing record for the caller's tenant

  /v1/billing/cancel:
    post:
      tags: [Billing]
      summary: Immediately cancel the caller's own subscription
      description: >
        Requires `Authorization: Bearer <api-key>`. Mounted the same way as
        `POST /v1/signup`/`POST /v1/billing/portal` — proxied to svc-auth,
        which resolves the caller's own tenantId server-side and calls
        svc-billing internally to cancel that tenant's Stripe subscription
        immediately (not at period end). There is no request body — the
        tenant to cancel is always the caller's own, never a body/path
        parameter (design/self-service-cancellation.md).
      operationId: billingCancel
      responses:
        "200":
          description: Subscription canceled
          content:
            application/json:
              schema:
                type: object
                properties:
                  tenantId: { type: string }
                  status: { type: string, enum: [canceled] }
                example:
                  tenantId: tenant_a1b2c3
                  status: canceled
        "400":
          description: Caller's tenant has no active subscription to cancel
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorEnvelope" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: No billing record for the caller's tenant

  /v1/whoami:
    get:
      tags: [Auth]
      summary: Return the caller's resolved tenant/role
      description: Resolves the bearer API key and returns the associated tenant id and role.
      operationId: whoami
      responses:
        "200":
          description: Resolved identity
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AuthContext"
              example:
                tenantId: tenant-acme-01
                role: user
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/templates:
    post:
      tags: [Templates]
      summary: Create a template (optionally generate immediately — feature 1b)
      description: >-
        When the request body includes an optional `generate` field, a
        document is generated from the newly-created template in the same
        call (see `CreateTemplateResponseDto` for the resulting 3-way
        response shape). Without `generate`, behavior is unchanged from
        create-only.
      operationId: createTemplate
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateTemplateRequestDto"
            examples:
              createOnly:
                summary: Create only (unchanged, backward compatible)
                value:
                  name: Order Confirmation
                  description: Sends a friendly order confirmation with a generated order number
                  body: "Hello <getParam('name')>, order #<createSeq('orderNo')>"
                  tags: [orders, email]
              createAndGenerate:
                summary: One-shot create + generate (feature 1b)
                value:
                  name: Invoice
                  body: "{ \"id\": \"<getRandomNumber(1,1000)>\" }"
                  generate:
                    seed: 42
      responses:
        "201":
          description: >-
            Template created. Response is a plain `TemplateDto` when
            `generate` was omitted, or `{ template, generation }` /
            `{ template, generationError }` when `generate` was present
            (see `CreateTemplateResponseDto`).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CreateTemplateResponseDto"
              examples:
                createOnly:
                  summary: generate omitted
                  value:
                    templateId: tpl_9f3a1c2e
                    tenantId: tenant-acme-01
                    name: Order Confirmation
                    description: Sends a friendly order confirmation with a generated order number
                    body: "Hello <getParam('name')>, order #<createSeq('orderNo')>"
                    tags: [orders, email]
                    validated: true
                    status: active
                    createdAt: "2026-07-23T09:00:00.000Z"
                    updatedAt: "2026-07-23T09:00:00.000Z"
                createAndGenerateSuccess:
                  summary: generate present, succeeded
                  value:
                    template:
                      templateId: tpl_1a2b3c4d
                      tenantId: tenant-acme-01
                      name: Invoice
                      body: "{ \"id\": \"<getRandomNumber(1,1000)>\" }"
                      tags: []
                      validated: true
                      status: active
                      createdAt: "2026-07-25T10:00:00.000Z"
                      updatedAt: "2026-07-25T10:00:00.000Z"
                    generation:
                      data: { id: "731" }
                      meta:
                        seed: 42
                        templateId: tpl_1a2b3c4d
                        generatedAt: "2026-07-25T10:00:00.000Z"
                createAndGenerateFailed:
                  summary: generate present, template persisted but generation failed at runtime
                  value:
                    template:
                      templateId: tpl_5e6f7a8b
                      tenantId: tenant-acme-01
                      name: NeedsParam
                      body: "{ \"v\": \"<getParam('sku')>\" }"
                      tags: []
                      validated: true
                      status: active
                      createdAt: "2026-07-25T10:00:00.000Z"
                      updatedAt: "2026-07-25T10:00:00.000Z"
                    generationError:
                      code: GENERATION_FAILED
                      message: "getParam: parameter 'sku' was not provided and has no default"
        "400":
          description: >-
            `VALIDATION_ERROR` (missing `name`/`body`), `INVALID_TEMPLATE`
            (structural problems incl. unbalanced for/if blocks or a
            template with zero placeholders — code `NO_PLACEHOLDERS` in
            `details`), or `UNKNOWN_FUNCTION` (body references a function
            outside the v1 catalog). Template is never saved in any of
            these cases, even if `generate` was present.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorEnvelope" }
              examples:
                validationError:
                  summary: Missing required field
                  value:
                    error:
                      code: VALIDATION_ERROR
                      message: "\"name\" is required"
                      details: { field: name }
                noPlaceholders:
                  summary: Template has no placeholders
                  value:
                    error:
                      code: INVALID_TEMPLATE
                      message: >-
                        Template body must contain at least one placeholder
                        (e.g. <getName()>) — a template with only literal
                        text cannot generate varying data
                      details: { reason: "Template body must contain at least one placeholder (e.g. <getName()>) — a template with only literal text cannot generate varying data", code: NO_PLACEHOLDERS }
                unknownFunction:
                  summary: Body references an unknown function
                  value:
                    error:
                      code: UNKNOWN_FUNCTION
                      message: "Unknown function 'notAFunction'"
                      details: { name: notAFunction }
        "401":
          $ref: "#/components/responses/Unauthorized"
    get:
      tags: [Templates]
      summary: List templates
      operationId: listTemplates
      parameters:
        - name: name
          in: query
          schema: { type: string }
        - name: status
          in: query
          schema: { type: string, enum: [active, archived] }
        - name: tags
          in: query
          description: Comma-separated list of tags
          schema: { type: string }
          example: "orders,email"
        - name: cursor
          in: query
          schema: { type: string }
        - name: limit
          in: query
          schema: { type: integer, default: 20 }
      responses:
        "200":
          description: Page of templates
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items: { $ref: "#/components/schemas/TemplateDto" }
                  nextCursor: { type: string }
              example:
                items:
                  - templateId: tpl_9f3a1c2e
                    tenantId: tenant-acme-01
                    name: Order Confirmation
                    body: "Hello <getParam('name')>, order #<createSeq('orderNo')>"
                    tags: [orders, email]
                    validated: true
                    status: active
                    createdAt: "2026-07-23T09:00:00.000Z"
                    updatedAt: "2026-07-23T09:00:00.000Z"
                nextCursor: "eyJvZmZzZXQiOjIwfQ=="
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/templates/generate:
    post:
      tags: [Templates]
      summary: Ad-hoc/debug generate — generate directly from a raw body, no persistence (feature 1a)
      description: >-
        Generates a document from a raw template body without creating a
        template record. Useful for quickly iterating on template syntax.
        Goes through the same billing/usage metering as persisted-template
        generation (keyed on tenantId, not templateId) — not a free bypass
        of usage billing. `createSeq`/durable sequence side effects still
        apply; callers should set `sequenceNamespace`/`variableNamespace`
        (e.g. `"debug"`) to avoid colliding with real tenant sequences.
      operationId: generateAdhoc
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AdhocGenerateRequestDto" }
            example:
              body: "{ \"name\": \"<getRandomFullName()>\" }"
              seed: 42
              sequenceNamespace: debug
              variableNamespace: debug
      responses:
        "200":
          description: Generated document
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AdhocGenerateResponseDto" }
              example:
                data: { name: Jane Doe }
                meta:
                  seed: 42
                  generatedAt: "2026-07-25T10:00:00.000Z"
        "400":
          description: >-
            `INVALID_TEMPLATE`/`UNKNOWN_FUNCTION` (malformed body, same
            static validation as template create) or `GENERATION_FAILED`
            (runtime evaluation error) — same error taxonomy as
            `POST /v1/templates/{templateId}/generate`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorEnvelope" }
              examples:
                generationFailed:
                  summary: Runtime evaluation error
                  value:
                    error:
                      code: GENERATION_FAILED
                      message: "getParam: parameter 'who' was not provided and has no default"
                      details: { reason: "getParam: parameter 'who' was not provided and has no default" }
                noPlaceholders:
                  summary: Static validation — template has no placeholders
                  value:
                    error:
                      code: INVALID_TEMPLATE
                      message: >-
                        Template body must contain at least one placeholder
                        (e.g. <getName()>) — a template with only literal
                        text cannot generate varying data
                      details: { reason: "Template body must contain at least one placeholder (e.g. <getName()>) — a template with only literal text cannot generate varying data", code: NO_PLACEHOLDERS }
                unknownFunction:
                  summary: Static validation — unknown function reference
                  value:
                    error:
                      code: UNKNOWN_FUNCTION
                      message: "Unknown function 'notAFunction'"
                      details: { name: notAFunction }
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/templates/{templateId}:
    parameters:
      - name: templateId
        in: path
        required: true
        schema: { type: string }
        example: tpl_9f3a1c2e
    get:
      tags: [Templates]
      summary: Get a template by id
      operationId: getTemplate
      responses:
        "200":
          description: Template
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TemplateDto" }
        "404":
          $ref: "#/components/responses/NotFound"
        "401":
          $ref: "#/components/responses/Unauthorized"
    put:
      tags: [Templates]
      summary: Update a template
      operationId: updateTemplate
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                description: { type: string }
                body: { type: string }
                tags:
                  type: array
                  items: { type: string }
            example:
              body: "Hello <getParam('name')>, your order #<createSeq('orderNo')> is confirmed!"
      responses:
        "200":
          description: Updated template
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TemplateDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "404":
          $ref: "#/components/responses/NotFound"
        "401":
          $ref: "#/components/responses/Unauthorized"
    delete:
      tags: [Templates]
      summary: Delete a template
      operationId: deleteTemplate
      responses:
        "200":
          description: The removed template record
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TemplateDto" }
        "404":
          $ref: "#/components/responses/NotFound"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/templates/{templateId}/generate:
    parameters:
      - name: templateId
        in: path
        required: true
        schema: { type: string }
        example: tpl_9f3a1c2e
    post:
      tags: [Templates]
      summary: Generate a document from a template
      operationId: generateFromTemplate
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/GenerateRequestDto" }
            example:
              seed: 123456789
              params:
                name: Jane Doe
              sequenceNamespace: default
              variableNamespace: default
      responses:
        "200":
          description: Generated document
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GenerateResponseDto" }
              example:
                data: "Hello Jane Doe, order #1001"
                meta:
                  seed: 123456789
                  templateId: tpl_9f3a1c2e
                  generatedAt: "2026-07-23T09:05:00.000Z"
        "400":
          $ref: "#/components/responses/BadRequest"
        "404":
          $ref: "#/components/responses/NotFound"
        "422":
          description: >
            Generation error (e.g. resource limits exceeded). `code` is one of
            `LOOP_LIMIT_EXCEEDED` (default 10,000 iterations),
            `NODE_LIMIT_EXCEEDED` (default 100,000 node evaluations),
            `EVALUATION_TIMEOUT` (default 2,000 ms),
            `OUTPUT_LIMIT_EXCEEDED` (cumulative rendered-output byte cap,
            default 8 MiB) or `GENERATION_ERROR`. `details` carries the
            `limit` that was exceeded plus a `kind` discriminator
            (`loopIterations` | `nodeEvaluations` | `timeout` | `outputBytes`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorEnvelope" }
              example:
                error:
                  code: OUTPUT_LIMIT_EXCEEDED
                  message: Template produced more than the maximum of 8388608 bytes of output
                  details: { limit: 8388608, kind: outputBytes, producedBytes: 8388621 }
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/sequences:
    post:
      tags: [Sequences]
      summary: Create a sequence
      operationId: createSequence
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, type]
              properties:
                name: { type: string }
                type: { type: string, enum: [number, string, uuid] }
                start: { type: number }
                step: { type: number }
            example:
              name: orderNo
              type: number
              start: 1000
              step: 1
      responses:
        "201":
          description: Sequence created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SequenceDto" }
              example:
                tenantId: tenant-acme-01
                name: orderNo
                type: number
                currentValue: 1000
                start: 1000
                step: 1
                createdAt: "2026-07-23T09:00:00.000Z"
                updatedAt: "2026-07-23T09:00:00.000Z"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
    get:
      tags: [Sequences]
      summary: List sequences
      operationId: listSequences
      parameters:
        - name: cursor
          in: query
          schema: { type: string }
        - name: limit
          in: query
          schema: { type: integer, default: 20 }
      responses:
        "200":
          description: Page of sequences
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items: { $ref: "#/components/schemas/SequenceDto" }
                  nextCursor: { type: string }
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/sequences/{name}:
    parameters:
      - name: name
        in: path
        required: true
        schema: { type: string }
        example: orderNo
    get:
      tags: [Sequences]
      summary: Get a sequence by name
      operationId: getSequence
      responses:
        "200":
          description: Sequence
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SequenceDto" }
        "404":
          $ref: "#/components/responses/NotFound"
        "401":
          $ref: "#/components/responses/Unauthorized"
    patch:
      tags: [Sequences]
      summary: Update a sequence
      operationId: patchSequence
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                currentValue: { type: number }
                step: { type: number }
            example:
              currentValue: 2000
      responses:
        "200":
          description: Updated sequence
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SequenceDto" }
        "404":
          $ref: "#/components/responses/NotFound"
        "401":
          $ref: "#/components/responses/Unauthorized"
    delete:
      tags: [Sequences]
      summary: Delete a sequence
      operationId: deleteSequence
      responses:
        "204":
          description: Deleted, no content
        "404":
          $ref: "#/components/responses/NotFound"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/sequences/{name}/bump:
    parameters:
      - name: name
        in: path
        required: true
        schema: { type: string }
        example: orderNo
    post:
      tags: [Sequences]
      summary: Bump (advance) a sequence by its step
      operationId: bumpSequence
      responses:
        "200":
          description: Sequence after bump
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SequenceDto" }
              example:
                tenantId: tenant-acme-01
                name: orderNo
                type: number
                currentValue: 1001
                start: 1000
                step: 1
                createdAt: "2026-07-23T09:00:00.000Z"
                updatedAt: "2026-07-23T09:06:00.000Z"
        "404":
          $ref: "#/components/responses/NotFound"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/batches:
    post:
      tags: [Batches]
      summary: Create a batch generation job
      description: >
        Small batches may be executed synchronously (200 with results),
        larger batches are queued and executed asynchronously (202).
        Template params: batch-level `params` are defaults for every
        document; each document's own `params` are shallow-merged over them
        (document keys win). Each document may also override the batch-level
        `sequenceNamespace`/`variableNamespace`. Params and namespaces of one
        document never affect another, and sync and async execution use the
        same resolved inputs.
      operationId: createBatch
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BatchSpec" }
            example:
              seed: 42424242
              params:
                locale: en-US
              sequenceNamespace: batch-2026-07-23
              variableNamespace: batch-2026-07-23
              documents:
                - templateId: tpl_9f3a1c2e
                  alias: order
                  count: 3
                  params:
                    name: Jane Doe
      responses:
        "202":
          description: Batch accepted for async processing
          content:
            application/json:
              schema:
                type: object
                properties:
                  batchId: { type: string }
                  status: { type: string, enum: [queued, running, completed, failed] }
                  seed: { type: number }
              example:
                batchId: batch_7d2e4f10
                status: queued
                seed: 42424242
        "200":
          description: >
            Batch executed synchronously (small batches). On success `status`
            is `completed` and `results` maps each document alias to the array
            of generated documents (the documents themselves, no per-document
            wrapper). If generation fails the response is still HTTP 200 with
            `status: failed` and an `error` object, and `results` is omitted.
          content:
            application/json:
              schema:
                type: object
                required: [batchId, status, seed]
                properties:
                  batchId: { type: string }
                  status: { type: string, enum: [queued, running, completed, failed] }
                  seed: { type: number }
                  results: { $ref: "#/components/schemas/BatchResults" }
                  error: { $ref: "#/components/schemas/BatchError" }
              examples:
                completed:
                  value:
                    batchId: batch_7d2e4f10
                    status: completed
                    seed: 42424242
                    results:
                      order:
                        - { orderNo: 1001, customer: Jane Doe, locale: en-US }
                        - { orderNo: 1002, customer: Jane Doe, locale: en-US }
                        - { orderNo: 1003, customer: Jane Doe, locale: en-US }
                failed:
                  value:
                    batchId: batch_7d2e4f10
                    status: failed
                    seed: 42424242
                    error:
                      code: TEMPLATE_FETCH_FAILED
                      message: "Failed to fetch template 'tpl_9f3a1c2e': HTTP 404"
        "400":
          description: >
            Validation error (e.g. `params` that is not a JSON object, an empty
            or non-string namespace, missing `templateId`/`alias`/`count`) or an
            invalid relation graph. Nothing is persisted or generated.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorEnvelope" }
              examples:
                invalidDocumentParams:
                  value:
                    error:
                      code: VALIDATION_ERROR
                      message: "document 'order' params must be a JSON object, got array"
                      details: { alias: order, field: params, receivedType: array }
                invalidBatchNamespace:
                  value:
                    error:
                      code: VALIDATION_ERROR
                      message: "sequenceNamespace must be a non-empty string, got number"
                      details: { field: sequenceNamespace, receivedType: number }
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/batches/{batchId}:
    parameters:
      - name: batchId
        in: path
        required: true
        schema: { type: string }
        example: batch_7d2e4f10
    get:
      tags: [Batches]
      summary: Get batch status and documents
      description: >
        Returns the batch's status and seed. Once `status` is `completed`,
        `results` maps each document alias to the array of generated documents
        (same shape as the synchronous `POST /v1/batches` 200 response). While
        `queued`/`running` there is no `results`; on `failed` there is an
        `error` object instead. The original request spec, tenant id and
        per-document metadata are not returned.
      operationId: getBatch
      responses:
        "200":
          description: Batch status (and results once completed)
          content:
            application/json:
              schema:
                type: object
                required: [batchId, status, seed]
                properties:
                  batchId: { type: string }
                  status: { type: string, enum: [queued, running, completed, failed] }
                  seed: { type: number }
                  results: { $ref: "#/components/schemas/BatchResults" }
                  error: { $ref: "#/components/schemas/BatchError" }
              examples:
                completed:
                  value:
                    batchId: batch_7d2e4f10
                    status: completed
                    seed: 42424242
                    results:
                      order:
                        - { orderNo: 1001, customer: Jane Doe, locale: en-US }
                        - { orderNo: 1002, customer: Jane Doe, locale: en-US }
                        - { orderNo: 1003, customer: Jane Doe, locale: en-US }
                running:
                  value:
                    batchId: batch_7d2e4f10
                    status: running
                    seed: 42424242
                failed:
                  value:
                    batchId: batch_7d2e4f10
                    status: failed
                    seed: 42424242
                    error:
                      code: TEMPLATE_FETCH_FAILED
                      message: "Failed to fetch template 'tpl_9f3a1c2e': HTTP 404"
        "404":
          $ref: "#/components/responses/NotFound"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/admin/function-weights:
    get:
      tags: [Admin]
      summary: List function weights (admin only)
      description: Requires the caller's API key to have role=admin.
      operationId: listFunctionWeights
      responses:
        "200":
          description: Function weights
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/FunctionWeightDto" }
              example:
                - functionName: randomInt
                  weight: 1
                  updatedAt: "2026-07-01T00:00:00.000Z"
                - functionName: randomWord
                  weight: 2
                  updatedAt: "2026-07-01T00:00:00.000Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"

  /v1/admin/function-weights/{functionName}:
    parameters:
      - name: functionName
        in: path
        required: true
        schema: { type: string }
        example: randomInt
    patch:
      tags: [Admin]
      summary: Update a function's weight (admin only)
      operationId: updateFunctionWeight
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [weight]
              properties:
                weight: { type: number }
            example:
              weight: 5
      responses:
        "200":
          description: Updated function weight
          content:
            application/json:
              schema: { $ref: "#/components/schemas/FunctionWeightDto" }
              example:
                functionName: randomInt
                weight: 5
                updatedAt: "2026-07-23T09:10:00.000Z"
                updatedBy: tenant-acme-01
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"

  /v1/usage:
    get:
      tags: [Usage]
      summary: Get tenant usage totals
      operationId: getUsage
      responses:
        "200":
          description: Usage
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TenantUsageDto" }
              example:
                tenantId: tenant-acme-01
                usageTotal: 15234
                asOf: "2026-07-23T09:15:00.000Z"
        "401":
          $ref: "#/components/responses/Unauthorized"

components:
  parameters:
    RequestId:
      name: x-request-id
      in: header
      required: false
      description: >
        Optional caller-supplied correlation id. Honoured verbatim and echoed
        back on the response; if omitted, the gateway generates a UUID.
        Accepted on every route.
      schema: { type: string, maxLength: 200 }
      example: 7f3c9b2e-1a4d-4c8f-9e2b-5d6a7c8e9f01

  headers:
    XRequestId:
      description: >
        Correlation id for this request (the caller-supplied `x-request-id`
        if one was sent, otherwise a generated UUID). Returned on every
        response, including error responses. Quote it in support requests.
      schema: { type: string }
      example: 7f3c9b2e-1a4d-4c8f-9e2b-5d6a7c8e9f01

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API-KEY
      description: "API key passed as: Authorization: Bearer <api-key>"

  responses:
    Unauthorized:
      description: Missing, malformed, or invalid API key
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorEnvelope" }
          example:
            error:
              code: UNAUTHORIZED
              message: Missing or invalid API key
              details: {}
    Forbidden:
      description: Caller is authenticated but lacks the required role
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorEnvelope" }
          example:
            error:
              code: FORBIDDEN
              message: Admin role required
              details: {}
    NotFound:
      description: Resource does not exist
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorEnvelope" }
          example:
            error:
              code: NOT_FOUND
              message: Template tpl_missing not found
              details: {}
    BadRequest:
      description: Validation or template/generation error
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorEnvelope" }
          example:
            error:
              code: VALIDATION_ERROR
              message: "\"name\" is required"
              details: { field: name }

  schemas:
    ErrorEnvelope:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message]
          properties:
            code: { type: string, example: VALIDATION_ERROR }
            message: { type: string, example: "\"name\" is required" }
            details: { type: object }

    AuthContext:
      type: object
      properties:
        tenantId: { type: string, example: tenant-acme-01 }
        role: { type: string, enum: [admin, user], example: user }

    TemplateDto:
      type: object
      properties:
        templateId: { type: string, example: tpl_9f3a1c2e }
        tenantId: { type: string, example: tenant-acme-01 }
        name: { type: string, example: Order Confirmation }
        description: { type: string, nullable: true }
        body: { type: string, example: "Hello <getParam('name')>, order #<createSeq('orderNo')>" }
        astCache:
          type: array
          items: {}
          nullable: true
        tags:
          type: array
          items: { type: string }
        validated: { type: boolean }
        warnings:
          type: array
          items: { type: string }
        status: { type: string, enum: [active, archived] }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }

    SequenceDto:
      type: object
      properties:
        tenantId: { type: string, example: tenant-acme-01 }
        name: { type: string, example: orderNo }
        type: { type: string, enum: [number, string, uuid] }
        currentValue: { type: number, example: 1000 }
        start: { type: number, example: 1000 }
        step: { type: number, example: 1 }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }

    BatchDocumentSpec:
      type: object
      required: [templateId, alias, count]
      properties:
        templateId: { type: string, example: tpl_9f3a1c2e }
        alias: { type: string, example: order }
        count: { type: integer, example: 3 }
        relations:
          type: object
          additionalProperties:
            oneOf:
              - type: string
              - type: object
                properties:
                  from: { type: string, description: "Field path '<parentAlias>.<field>' (e.g. 'customer.id'). A bare alias resolves to the whole parent document." }
                  strategy: { type: string, enum: [round-robin] }
        params:
          type: object
          additionalProperties: true
          description: >
            Template params (read with getParam) for every document of this
            alias. Shallow-merged over the batch-level `params`; keys here win.
            Must be a JSON object, otherwise 400 VALIDATION_ERROR.
          example: { name: Jane Doe }
        sequenceNamespace:
          type: string
          minLength: 1
          description: Overrides the batch-level sequenceNamespace for this alias only.
        variableNamespace:
          type: string
          minLength: 1
          description: Overrides the batch-level variableNamespace for this alias only.

    BatchSpec:
      type: object
      required: [documents]
      properties:
        seed: { type: number, example: 42424242 }
        params:
          type: object
          additionalProperties: true
          description: >
            Default template params for every document in the batch. Each
            document's own `params` are shallow-merged over these (document
            keys win). Must be a JSON object, otherwise 400 VALIDATION_ERROR.
          example: { locale: en-US }
        sequenceNamespace:
          type: string
          minLength: 1
          example: batch-2026-07-23
          description: Default sequence namespace for every document (a document may override it).
        variableNamespace:
          type: string
          minLength: 1
          example: batch-2026-07-23
          description: Default variable namespace for every document (a document may override it).
        documents:
          type: array
          items: { $ref: "#/components/schemas/BatchDocumentSpec" }

    BatchResults:
      type: object
      description: >
        Generated documents keyed by document alias (the `alias` values from
        the request's `documents[]`). Each value is an array of `count`
        generated documents, in generation order — the documents themselves,
        exactly as the template renders them (plus any injected relation
        fields), with no per-document wrapper. A document is usually an
        object, but can be any JSON value the template produces (array,
        string, number, boolean or null), e.g. `[[7,3,3,0],[8,2,2,0]]` or
        `["plain 7","plain 8"]`. Only present when `status` is `completed`.
      additionalProperties:
        type: array
        items: {}
      example:
        order:
          - { orderNo: 1001, customer: Jane Doe, locale: en-US }
          - { orderNo: 1002, customer: Jane Doe, locale: en-US }

    BatchError:
      type: object
      description: Why the batch failed. Only present when `status` is `failed`.
      required: [code, message]
      properties:
        code: { type: string, example: TEMPLATE_FETCH_FAILED }
        message: { type: string, example: "Failed to fetch template 'tpl_9f3a1c2e': HTTP 404" }

    FunctionWeightDto:
      type: object
      properties:
        functionName: { type: string, example: randomInt }
        weight: { type: number, example: 1 }
        updatedAt: { type: string, format: date-time }
        updatedBy: { type: string, nullable: true, example: tenant-acme-01 }

    TenantUsageDto:
      type: object
      properties:
        tenantId: { type: string, example: tenant-acme-01 }
        usageTotal: { type: number, example: 15234 }
        asOf: { type: string, format: date-time }

    GenerateRequestDto:
      type: object
      properties:
        seed: { type: number, example: 123456789 }
        params:
          type: object
          example: { name: Jane Doe }
        context:
          type: object
          properties:
            parentIds: { type: object }
            values: { type: object }
        sequenceNamespace: { type: string, example: default }
        variableNamespace: { type: string, example: default }

    GenerateResponseDto:
      type: object
      properties:
        data: {}
        meta:
          type: object
          properties:
            seed: { type: number, example: 123456789 }
            templateId: { type: string, example: tpl_9f3a1c2e }
            generatedAt: { type: string, format: date-time }
            documentSeed: { type: number, example: 123456789 }

    AdhocGenerateRequestDto:
      description: >-
        Feature 1a (ad-hoc/debug generation) — same fields as
        `GenerateRequestDto` plus the required raw template `body`. Nothing
        is persisted; useful for quickly iterating on a template before
        committing it via `POST /v1/templates`.
      type: object
      required: [body]
      properties:
        body:
          type: string
          example: "{ \"name\": \"<getRandomFullName()>\" }"
        seed: { type: number, example: 42 }
        params:
          type: object
          example: {}
        context:
          type: object
          properties:
            parentIds: { type: object }
            values: { type: object }
        sequenceNamespace:
          type: string
          example: debug
          description: >-
            Recommended for ad-hoc calls to avoid colliding with real
            tenant sequences created by persisted templates.
        variableNamespace:
          type: string
          example: debug

    AdhocGenerateResponseDto:
      description: >-
        Same shape as `GenerateResponseDto` but `meta` has no `templateId`
        — nothing was persisted.
      type: object
      properties:
        data: {}
        meta:
          type: object
          properties:
            seed: { type: number, example: 42 }
            generatedAt: { type: string, format: date-time }

    CreateTemplateRequestDto:
      type: object
      required: [name, body]
      properties:
        name: { type: string }
        description: { type: string }
        body: { type: string }
        tags:
          type: array
          items: { type: string }
        generate:
          description: >-
            Feature 1b (one-shot create+generate, issue #5). When present,
            the template is created and, immediately after, a document is
            generated from it using these options (same fields as
            `GenerateRequestDto` minus `sequenceNamespace`/
            `variableNamespace`, which follow the template's own tenant
            defaults). Omit this field for the original create-only
            behavior.
          type: object
          properties:
            seed: { type: number, example: 42 }
            params: { type: object }
            context: { type: object }

    GenerationErrorDto:
      description: >-
        Inline generation error embedded in a 201 create+generate response
        when the template was persisted successfully but the immediate
        generation attempt failed at runtime (e.g. a required param with no
        default). Distinct from the top-level `ErrorEnvelope` used for
        actual HTTP error responses — this always accompanies a 201 with a
        populated `template`.
      type: object
      properties:
        code: { type: string, example: GENERATION_FAILED }
        message: { type: string, example: "getParam: parameter 'sku' was not provided and has no default" }

    CreateTemplateResponseDto:
      description: >-
        Three possible response shapes depending on the request (feature
        1b):
          1. `generate` absent — plain `TemplateDto` (unchanged, backward
             compatible).
          2. `generate` present and generation succeeds — `{ template,
             generation }`.
          3. `generate` present but generation fails at runtime — `{
             template, generationError }` (the template was still
             persisted; only 201 create is not undone by a generate-time
             failure). `generation` and `generationError` are mutually
             exclusive.
      oneOf:
        - $ref: "#/components/schemas/TemplateDto"
        - type: object
          required: [template, generation]
          properties:
            template: { $ref: "#/components/schemas/TemplateDto" }
            generation: { $ref: "#/components/schemas/GenerateResponseDto" }
        - type: object
          required: [template, generationError]
          properties:
            template: { $ref: "#/components/schemas/TemplateDto" }
            generationError: { $ref: "#/components/schemas/GenerationErrorDto" }
