openapi: 3.1.0
info:
  title: ALIA Hub — API pública de formularios
  version: "1.0"
  description: |
    Envía formularios de una web a ALIA Hub (crea o actualiza un registro del CRM / Help Desk).
    Cada formulario se configura en Hub (Staff) con su mapeo de campos; su contrato exacto por
    formulario está en `GET /forms/{publicKey}/schema` (JSON Schema).

    **Semántica de reintentos:** 2xx = guardado (o ya estaba: `duplicate: true`); 4xx = NO reintentar
    (corrige el envío); 429 y 5xx = reintentar con backoff (respeta `Retry-After`). Envía siempre
    `Idempotency-Key` (uuid por envío): reintentar no duplica.

    **Dos modos por formulario:** `PUBLIC` (la llave `pk_…` de la URL basta; navegador o servidor;
    valida Origin, honeypot `_gotcha` y límite por IP) y `SERVER` (exige `Authorization: Bearer sk_…`,
    firma HMAC opcional/obligatoria, allowlist de IP opcional; devuelve el id del registro).
servers:
  - url: https://hub.usealia.mx/api/v1
paths:
  /health:
    get:
      summary: Salud de la API
      description: Confirma que la API y su base de datos responden. Sin datos.
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Health" } } } }
        "503": { description: Base de datos no disponible (reintentar), content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
  /forms/{publicKey}:
    post:
      summary: Enviar un formulario
      parameters:
        - { name: publicKey, in: path, required: true, schema: { type: string, example: "pk_<tenant>_<rand>" } }
        - { name: Idempotency-Key, in: header, schema: { type: string }, description: "Recomendado. Mismo valor = mismo resultado, sin duplicar (también con envíos simultáneos)." }
        - { name: X-Test-Mode, in: header, schema: { type: string, enum: ["true"] }, description: "Valida todo sin guardar nada." }
        - { name: Authorization, in: header, schema: { type: string, example: "Bearer sk_…" }, description: "Obligatorio en modo SERVER." }
        - { name: X-Timestamp, in: header, schema: { type: string }, description: "ms desde epoch. Con X-Signature. Ventana de 5 min." }
        - { name: X-Signature, in: header, schema: { type: string }, description: "HMAC-SHA256 hex de (body + timestamp) con la credencial secreta." }
        - { name: X-External-Id, in: header, schema: { type: string }, description: "Solo modo SERVER. Mismo id = actualiza el registro en vez de crear otro." }
        - { name: X-Source-System, in: header, schema: { type: string, default: api }, description: "Solo modo SERVER. Sistema de origen del id externo." }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/Submission" }
          application/x-www-form-urlencoded:
            schema: { type: object, additionalProperties: { type: string } }
          multipart/form-data:
            schema: { type: object, additionalProperties: { type: string } }
      responses:
        "200": { description: Guardado (o ya guardado), content: { application/json: { schema: { $ref: "#/components/schemas/Ok" } } } }
        "303": { description: "<form> HTML sin JavaScript: redirige a la URL de gracias del formulario." }
        "400": { description: Cuerpo inválido, content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
        "401": { description: "Credencial o firma inválida (modo SERVER).", content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
        "403": { description: "Origen o IP no autorizados.", content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
        "404": { description: "Formulario inexistente o pausado.", content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
        "409": { description: "El módulo destino no está contratado.", content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
        "422": { description: "Validación: `errors[]` lista TODOS los problemas.", content: { application/json: { schema: { $ref: "#/components/schemas/ValidationError" } } } }
        "429": { description: "Límite excedido; reintenta tras Retry-After.", headers: { Retry-After: { schema: { type: string } } }, content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
        "500": { description: "Error interno; reintenta con backoff.", content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
  /forms/{publicKey}/schema:
    get:
      summary: Contrato del formulario (JSON Schema)
      description: "Generado del mapeo y de los tipos reales de los campos (listas con sus opciones, correo, teléfono, fecha…). En modo SERVER exige `Authorization: Bearer`."
      parameters:
        - { name: publicKey, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: Contrato, content: { application/json: { schema: { $ref: "#/components/schemas/FormSchema" } } } }
        "401": { description: Credencial requerida (modo SERVER) }
        "404": { description: Formulario inexistente }
components:
  schemas:
    Submission:
      type: object
      description: Los campos del formulario van al nivel raíz (los nombres los define el mapeo; ver /schema). `consent` y `meta` son opcionales.
      additionalProperties: true
      properties:
        consent:
          type: object
          additionalProperties: false
          description: Evidencia de consentimiento. Se guarda como evento inmutable ligado al registro (LFPDPPP).
          properties:
            consentAt: { type: string, format: date-time }
            termsVersion: { type: string, maxLength: 60 }
            purposes: { type: array, maxItems: 12, items: { type: string, maxLength: 60 } }
        meta:
          type: object
          additionalProperties: false
          description: Origen del envío. En modo SERVER, `ip`/`userAgent` son los de la PERSONA (los manda tu backend).
          properties:
            source: { type: string, maxLength: 120 }
            utm: { type: object, maxProperties: 12, additionalProperties: { type: string, maxLength: 200 } }
            ip: { type: string, maxLength: 64 }
            userAgent: { type: string, maxLength: 400 }
    Ok:
      type: object
      required: [status, message]
      properties:
        status: { type: string, enum: [ok] }
        message: { type: string }
        id: { type: string, description: "Solo modo SERVER: id del registro." }
        object: { type: string, description: "Solo modo SERVER: tipo de registro (lead, ticket…)." }
        created: { type: boolean, description: "Solo modo SERVER: false si fue una actualización por X-External-Id." }
        duplicate: { type: boolean, description: "Solo modo SERVER: true si era un reintento con la misma Idempotency-Key." }
    Error:
      type: object
      required: [status, code, message, retryable]
      properties:
        status: { type: string, enum: [error] }
        code:
          type: string
          enum: [formulario_no_encontrado, formulario_inactivo, origen_no_permitido, ip_not_allowed, unauthorized, invalid_signature, parametros_invalidos, campo_requerido_faltante, tipo_invalido, objeto_desactivado, rate_limited, internal_error, database_unavailable]
        message: { type: string }
        retryable: { type: boolean, description: "true solo en 429 y 5xx." }
    ValidationError:
      allOf:
        - $ref: "#/components/schemas/Error"
        - type: object
          properties:
            field: { type: string, description: "Primer campo con problema (compatibilidad v1)." }
            errors:
              type: array
              items:
                type: object
                properties:
                  field: { type: string }
                  code: { type: string, enum: [required, invalid_type, invalid_option, invalid_format] }
                  message: { type: string }
    Health:
      type: object
      properties:
        status: { type: string, enum: [ok] }
        version: { type: string }
        time: { type: string, format: date-time }
    FormSchema:
      type: object
      properties:
        status: { type: string, enum: [ok] }
        schemaVersion: { type: string }
        form: { type: object, properties: { name: { type: string }, mode: { type: string, enum: [PUBLIC, SERVER] }, object: { type: string }, active: { type: boolean } } }
        jsonSchema: { type: object, description: "JSON Schema 2020-12 del cuerpo del envío." }
        headers: { type: object, additionalProperties: { type: string } }
