openapi: 3.1.0
info:
  title: Pontiun API
  version: "2026-10-19"
  description: |
    API pública de Pontiun para responder por Messenger, Instagram y WhatsApp
    y recibir los eventos entrantes en el webhook de cada conexión.

    Generado a partir de las rutas de `apps/web/app/api/meta/**` y limitado a
    los endpoints publicados en https://docs.pontiun.com/api.

    ## Convenciones

    - Cuerpos en `application/json`; fechas en ISO-8601 UTC; ids como strings.
    - Toda respuesta de error trae `error`. Cuando Meta rechazó el envío, `meta`
      trae la respuesta original de Graph.
    - Un `Idempotency-Key` repetido devuelve `200` con el resultado original y
      `resender.idempotentReplay: true`, sin volver a llamar a Meta ni consumir
      cuota.
    - Solo consume cuota el envío que Meta aceptó.
    - En WhatsApp `Idempotency-Key` es obligatoria y la ventana de 24 horas se
      evalúa antes de llamar a Meta (`409` si está cerrada).
  contact:
    email: info@pontiun.com
externalDocs:
  description: Documentación pública
  url: https://docs.pontiun.com/api

servers:
  - url: https://pontiun.com
    description: Producción

security:
  - ApiKey: []

tags:
  - name: Messenger
    description: Mensajes de páginas de Facebook.
  - name: Instagram Direct
    description: Mensajes directos de cuentas profesionales de Instagram.
  - name: Instagram Comments
    description: Respuestas públicas y privadas a comentarios de Instagram.
  - name: WhatsApp
    description: Mensajes y plantillas desde números de WhatsApp Business conectados.
  - name: Connections
    description: Conexiones activas del tenant y la URL de su webhook.
  - name: Webhooks
    description: Eventos que Pontiun entrega al webhook configurado por conexión.

paths:
  /api/meta/send:
    post:
      tags: [Messenger]
      operationId: sendMessengerMessage
      summary: Enviar mensaje de Messenger
      description: |
        Envía texto **o** un adjunto por URL (nunca ambos) a un contacto de una
        página de Facebook conectada. El page access token se resuelve en el
        servidor.

        Destino en una de dos formas (ADR 0019):
        - `conversationId` solo, tomado del `conversation.id` del webhook.
        - `pageId` + `recipientId`; si además viene `conversationId`, debe
          coincidir con ese par.

        Messenger solo permite responder dentro de las 24 horas desde el último
        mensaje del contacto y trunca el texto a 2000 caracteres.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
        - $ref: "#/components/parameters/RequestId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MessengerSendRequest"
            examples:
              texto:
                summary: Texto respondiendo a un webhook
                value:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  reply: "¡Hola! Tenemos ese modelo en talle 38 y 40."
              contacto:
                summary: Texto por pageId + recipientId
                value:
                  pageId: "123456789012345"
                  recipientId: "9876543210987654"
                  reply: "¡Hola! Tenemos ese modelo en talle 38 y 40."
              adjunto:
                summary: Adjunto por URL
                value:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  attachment:
                    type: image
                    url: https://cdn.example.com/catalogo/zapatilla-38.jpg
      responses:
        "200":
          description: Meta aceptó el mensaje (o replay idempotente).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageSendResponse"
              example:
                meta:
                  message_id: m_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789
                resender:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  messageId: 0c9d2f6e-3b7a-4e1d-8f5c-2a1b3c4d5e6f
                  status: sent
        "400":
          $ref: "#/components/responses/MessengerBadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          $ref: "#/components/responses/QuotaExceeded"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/SendTargetNotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "502":
          $ref: "#/components/responses/MetaUnreachable"
        default:
          $ref: "#/components/responses/MetaRejectedMessage"

  /api/meta/instagram/send:
    post:
      tags: [Instagram Direct]
      operationId: sendInstagramMessage
      summary: Enviar mensaje directo de Instagram
      description: |
        Envía texto **o** un adjunto por URL (nunca ambos) a un contacto de una
        cuenta profesional de Instagram conectada. El body es el mismo que el
        de Messenger.

        `pageId` es el IG user id de la cuenta profesional (`page.metaPageId`
        del webhook) y `recipientId` el IGSID del contacto
        (`conversation.contactId`). También acepta `conversationId` solo.

        Instagram aplica su ventana de 24 horas y un máximo de 1000 bytes UTF-8
        al texto (no aplica a los adjuntos).

        Adjuntos que acepta Instagram (los valida Meta al descargar la URL, no
        Pontiun):

        | `type`  | Formatos               | Máximo |
        |---------|------------------------|--------|
        | `image` | png, jpeg              | 8 MB   |
        | `audio` | aac, m4a, wav, mp4     | 25 MB  |
        | `video` | mp4, ogg, avi, mov, webm | 25 MB |
        | `file`  | pdf                    | 25 MB  |

        Si Meta rechaza un adjunto en Instagram la respuesta no trae `code`
        estable (Meta no documenta subcodes de adjunto para este canal): el
        motivo va en `error` y la respuesta original de Graph en `meta`.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
        - $ref: "#/components/parameters/RequestId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/InstagramSendRequest"
            examples:
              texto:
                summary: Texto por pageId + recipientId
                value:
                  pageId: "17841400000000000"
                  recipientId: "1234567890123456"
                  reply: "¡Hola! Tenemos ese modelo en talle 38 y 40."
              documento:
                summary: Documento PDF respondiendo a un webhook
                value:
                  conversationId: 9a8b7c6d-5e4f-4a3b-2c1d-0e9f8a7b6c5d
                  attachment:
                    type: file
                    url: https://cdn.example.com/catalogo/lista-de-precios.pdf
              imagen:
                summary: Imagen por URL
                value:
                  conversationId: 9a8b7c6d-5e4f-4a3b-2c1d-0e9f8a7b6c5d
                  attachment:
                    type: image
                    url: https://cdn.example.com/catalogo/zapatilla-38.jpg
      responses:
        "200":
          description: Meta aceptó el mensaje (o replay idempotente).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageSendResponse"
              example:
                meta:
                  message_id: aWdfZG1faXRlbToxOklHTWVzc2FnZUlEOjE3ODQxNDAwMDAwMDAwMDAw
                resender:
                  conversationId: 9a8b7c6d-5e4f-4a3b-2c1d-0e9f8a7b6c5d
                  messageId: 1b2c3d4e-5f6a-4b7c-8d9e-0f1a2b3c4d5e
                  status: sent
        "400":
          $ref: "#/components/responses/InstagramSendBadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          $ref: "#/components/responses/QuotaExceeded"
        "403":
          $ref: "#/components/responses/ForbiddenInstagram"
        "404":
          $ref: "#/components/responses/SendTargetNotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "502":
          $ref: "#/components/responses/MetaUnreachable"
        default:
          $ref: "#/components/responses/MetaRejectedMessage"

  /api/meta/instagram/comments/reply:
    post:
      tags: [Instagram Comments]
      operationId: replyToInstagramComment
      summary: Responder públicamente a un comentario de Instagram
      description: |
        Publica una respuesta bajo un comentario recibido por webhook.
        `commentId` es el id de Meta del comentario (`comment.igCommentId`),
        no el uuid de Pontiun. Máximo 2200 caracteres.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
        - $ref: "#/components/parameters/RequestId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CommentReplyRequest"
            example:
              pageId: "17841400000000000"
              commentId: "17900000000000000"
              reply: "¡Gracias! Te escribimos por privado con el precio."
      responses:
        "200":
          description: Meta publicó la respuesta (o replay idempotente).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CommentReplyResponse"
              example:
                meta:
                  id: "17999999999999999"
                resender:
                  commentId: 8f1c2d3e-4a5b-4c6d-8e7f-9a0b1c2d3e4f
                  igCommentId: "17999999999999999"
                  status: sent
        "400":
          $ref: "#/components/responses/CommentBadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          $ref: "#/components/responses/QuotaExceeded"
        "403":
          $ref: "#/components/responses/ForbiddenInstagram"
        "404":
          $ref: "#/components/responses/CommentNotFound"
        "502":
          $ref: "#/components/responses/MetaUnreachable"
        default:
          $ref: "#/components/responses/MetaRejectedComment"

  /api/meta/instagram/comments/private-reply:
    post:
      tags: [Instagram Comments]
      operationId: privateReplyToInstagramComment
      summary: Responder por privado a un comentario de Instagram
      description: |
        Envía un mensaje directo a quien escribió el comentario. El
        destinatario sale del comentario guardado, nunca del body.

        Reglas de Instagram: una sola respuesta privada por comentario, dentro
        de los 7 días, y el comentario debe seguir existiendo. Un segundo
        intento deliberado responde `409`. Máximo 1000 bytes UTF-8.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
        - $ref: "#/components/parameters/RequestId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CommentReplyRequest"
            example:
              pageId: "17841400000000000"
              commentId: "17900000000000000"
              reply: "¡Hola! El precio es $45.000 con envío incluido. ¿Te lo reservo?"
      responses:
        "200":
          description: Meta aceptó el mensaje (o replay idempotente).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageSendResponse"
              example:
                meta:
                  message_id: aWdfZG1faXRlbToxOklHTWVzc2FnZUlEOjE3ODQxNDAwMDAwMDAwMDAw
                  recipient_id: "1234567890123456"
                resender:
                  conversationId: c3a1b2d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d
                  messageId: 9b22c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d
                  status: sent
        "400":
          $ref: "#/components/responses/PrivateReplyBadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          $ref: "#/components/responses/QuotaExceeded"
        "403":
          $ref: "#/components/responses/ForbiddenInstagram"
        "404":
          $ref: "#/components/responses/CommentNotFound"
        "409":
          description: El comentario ya recibió su única respuesta privada.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/PrivateReplyConflict"
              example:
                error: "this comment already received a private reply: Instagram allows exactly one per comment"
                resender:
                  conversationId: c3a1b2d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d
                  messageId: 9b22c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d
                  status: sent
        "502":
          $ref: "#/components/responses/MetaUnreachable"
        default:
          $ref: "#/components/responses/MetaRejectedMessage"

  /api/meta/whatsapp/send:
    post:
      tags: [WhatsApp]
      operationId: sendWhatsappMessage
      summary: Enviar mensaje de WhatsApp
      description: |
        Envía texto **o** un adjunto por URL (nunca ambos) a un contacto desde
        un número de WhatsApp conectado. El token del negocio se resuelve en el
        servidor.

        El body es el mismo que el de Messenger a propósito (ADR 0019): un
        cliente que atiende los tres canales solo cambia la URL. `pageId` es el
        `phone_number_id` del número conectado y `recipientId` es el teléfono
        del contacto en formato internacional.

        Destino en una de dos formas:
        - `conversationId` solo, tomado del `conversation.id` del webhook.
        - `pageId` + `recipientId`; si además viene `conversationId`, debe
          coincidir con ese par. El teléfono se normaliza a dígitos (sin `+`,
          espacios ni guiones), igual que el `wa_id` de los entrantes.

        **Ventana de 24 horas.** Pontiun la evalúa localmente antes de llamar
        a Meta: si el contacto no escribió en las últimas 24 horas (o nunca
        escribió), responde `409` con `requiresTemplate: true` sin consumir
        cuota. En ese caso hay que usar
        `POST /api/meta/whatsapp/templates/send`.

        **`Idempotency-Key` es obligatoria** en WhatsApp: un duplicado le llega
        al teléfono del cliente final.

        Texto: máximo 4096 caracteres. Adjuntos: `image`, `video` y `audio`
        llegan con ese mismo tipo y se ven en el chat; `file` se envía como
        `document` de Cloud API.

        **Pie de foto.** `attachment.caption` (opcional, solo WhatsApp) es el
        texto que se ve debajo del adjunto, en el mismo mensaje. Vale para
        `image`, `video` y `file`; en `audio` responde `400`
        (`attachment_caption_unsupported`) porque WhatsApp no lo muestra.
        Máximo 1024 caracteres. Vacío o `null` es "sin pie de foto".

        Pontiun no hospeda media: Meta descarga el
        archivo desde la URL y lo cachea ~10 minutos, así que la URL no puede
        ser de un solo uso ni caducar en segundos. Si el origen no responde, el
        envío falla con `code: attachment_fetch_failed`.
      parameters:
        - $ref: "#/components/parameters/WhatsappIdempotencyKey"
        - $ref: "#/components/parameters/RequestId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/WhatsappSendRequest"
            examples:
              texto:
                summary: Texto respondiendo a un webhook
                value:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  reply: "¡Hola! Tu pedido #8841 ya salió."
              contacto:
                summary: Texto por pageId (phone_number_id) + recipientId (teléfono)
                value:
                  pageId: "109876543210987"
                  recipientId: "+52 55 1234 5678"
                  reply: "¡Hola! Tu pedido #8841 ya salió."
              imagen:
                summary: Imagen por URL con pie de foto
                value:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  attachment:
                    type: image
                    url: https://cdn.example.com/pedidos/8841.png
                    caption: Así quedó tu pedido #8841.
              adjunto:
                summary: Documento por URL
                value:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  attachment:
                    type: file
                    url: https://cdn.example.com/facturas/8841.pdf
      responses:
        "200":
          description: Meta aceptó el mensaje (o replay idempotente).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageSendResponse"
              example:
                meta:
                  messaging_product: whatsapp
                  contacts:
                    - input: "5215512345678"
                      wa_id: "5215512345678"
                  messages:
                    - id: wamid.HBgNNTIxNTUxMjM0NTY3OBUCABEYEjBBQkNERUYxMjM0NTY3ODkwAA==
                resender:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  messageId: 0c9d2f6e-3b7a-4e1d-8f5c-2a1b3c4d5e6f
                  status: sent
        "400":
          $ref: "#/components/responses/WhatsappSendBadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          $ref: "#/components/responses/QuotaExceeded"
        "403":
          $ref: "#/components/responses/ForbiddenWhatsapp"
        "404":
          $ref: "#/components/responses/SendTargetNotFound"
        "409":
          $ref: "#/components/responses/WhatsappWindowClosed"
        "429":
          $ref: "#/components/responses/RateLimited"
        "502":
          $ref: "#/components/responses/WhatsappUnreachable"
        default:
          $ref: "#/components/responses/WhatsappMetaRejected"

  /api/meta/whatsapp/templates/send:
    post:
      tags: [WhatsApp]
      operationId: sendWhatsappTemplate
      summary: Enviar plantilla de WhatsApp
      description: |
        Envía una plantilla aprobada (ADR 0024). Es la forma de escribirle a un
        contacto con la ventana de 24 horas cerrada o que nunca escribió: esta
        ruta **no** evalúa la ventana.

        Destino, `Idempotency-Key` (obligatoria), controles de cuenta y forma
        de la respuesta son los mismos de `POST /api/meta/whatsapp/send`.

        `template` usa el vocabulario de Cloud API: `name`, `language` (código
        como `es_MX` o `en_US`) y `components` opcional, que se reenvía tal cual
        a Meta (Pontiun solo valida que sea un array). Si la copia local del
        catálogo sabe que la plantilla no está `APPROVED`, responde `409
        template_not_approved` sin llamar a Meta; si no la conoce, envía y
        decide Meta.

        Disponible también en el plan Free. Consume 1 de cuota solo si Meta
        aceptó. Meta factura las plantillas directo al método de pago de la
        WABA, no a través de Pontiun.
      parameters:
        - $ref: "#/components/parameters/WhatsappIdempotencyKey"
        - $ref: "#/components/parameters/RequestId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/WhatsappTemplateSendRequest"
            examples:
              sinVariables:
                summary: Plantilla sin variables
                value:
                  pageId: "109876543210987"
                  recipientId: "+52 55 1234 5678"
                  template:
                    name: hello_world
                    language: en_US
              conVariables:
                summary: Plantilla con variables en el cuerpo
                value:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  template:
                    name: pedido_enviado
                    language: es_MX
                    components:
                      - type: body
                        parameters:
                          - type: text
                            text: Ana
                          - type: text
                            text: "#8841"
              conEncabezado:
                summary: Plantilla con imagen en el encabezado
                value:
                  pageId: "109876543210987"
                  recipientId: "5215512345678"
                  template:
                    name: promo_temporada
                    language: es_MX
                    components:
                      - type: header
                        parameters:
                          - type: image
                            image:
                              link: https://cdn.example.com/promo.jpg
                      - type: body
                        parameters:
                          - type: text
                            text: "20%"
      responses:
        "200":
          description: Meta aceptó la plantilla (o replay idempotente).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageSendResponse"
              example:
                meta:
                  messaging_product: whatsapp
                  contacts:
                    - input: "5215512345678"
                      wa_id: "5215512345678"
                  messages:
                    - id: wamid.HBgNNTIxNTUxMjM0NTY3OBUCABEYEjBBQkNERUYxMjM0NTY3ODkwAA==
                      message_status: accepted
                resender:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  messageId: 0c9d2f6e-3b7a-4e1d-8f5c-2a1b3c4d5e6f
                  status: sent
        "400":
          $ref: "#/components/responses/WhatsappTemplateBadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          $ref: "#/components/responses/QuotaExceeded"
        "403":
          $ref: "#/components/responses/ForbiddenWhatsapp"
        "404":
          $ref: "#/components/responses/SendTargetNotFound"
        "409":
          $ref: "#/components/responses/WhatsappTemplateNotApproved"
        "429":
          $ref: "#/components/responses/RateLimited"
        "502":
          $ref: "#/components/responses/WhatsappUnreachable"
        default:
          $ref: "#/components/responses/WhatsappMetaRejected"

  /api/meta/whatsapp/media/{id}:
    get:
      tags: [WhatsApp]
      operationId: downloadWhatsappMedia
      summary: Descargar el adjunto de un mensaje de WhatsApp
      description: |
        Devuelve el archivo (imagen, audio, vídeo, documento o sticker) de un
        mensaje de WhatsApp, guardado en Pontiun. Es la URL que llega en
        `message.attachment.url` del evento de WhatsApp.

        **Dos formas de autenticar:**

        - **Link firmado.** La URL del evento ya trae `exp` y `sig` y se abre
          tal cual, sin cabeceras: en el navegador, en un `<img>` o en un nodo
          HTTP de n8n. Vence a las 24 h (`details.urlExpiresAt`). Cualquiera
          que tenga el link puede abrirlo hasta entonces: no lo publiques.
        - **API key.** La misma URL sin `exp` ni `sig`, con
          `Authorization: Bearer <api key>`. Sirve siempre, también después de
          que el link venció.

        Soporta `Range` (`206`), así que un audio o un vídeo se pueden
        adelantar en un reproductor. Los archivos se conservan 180 días desde
        que llegó el mensaje.
      security:
        - {}
        - ApiKey: []
      parameters:
        - name: id
          in: path
          required: true
          description: "`message.id` del evento (uuid de Pontiun, no el `wamid`)."
          schema:
            type: string
            format: uuid
        - name: exp
          in: query
          required: false
          description: Vencimiento del link firmado, en epoch segundos. Viene en la URL del evento; no se arma a mano.
          schema:
            type: string
            pattern: "^[0-9]+$"
        - name: sig
          in: query
          required: false
          description: Firma del link. Viene en la URL del evento; no se arma a mano.
          schema:
            type: string
        - name: Range
          in: header
          required: false
          schema:
            type: string
          example: bytes=0-1023
      responses:
        "200":
          description: El archivo completo. `content-type` es el MIME real del adjunto.
          headers:
            accept-ranges:
              schema:
                type: string
                const: bytes
            cache-control:
              schema:
                type: string
                const: private, max-age=0, no-store
          content:
            "*/*":
              schema:
                type: string
                format: binary
        "206":
          description: El rango pedido con `Range`.
          content:
            "*/*":
              schema:
                type: string
                format: binary
        "401":
          description: |
            Sin credencial válida: link vencido o alterado, y sin API key (o
            con una inválida). Con un link vencido, repetí el pedido sin
            `exp`/`sig` y con la API key.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: unauthorized
        "404":
          description: El mensaje no existe, es de otro tenant o no tiene adjunto descargable.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: not_found
        "409":
          description: |
            El mensaje tiene adjunto pero el archivo no está disponible.
            `status` dice por qué: `failed` (no se pudo bajar de WhatsApp),
            `deleted` (pasaron los 180 días) o `unavailable` (WhatsApp nunca
            lo ofreció, como en el historial de más de 14 días). En los tres
            casos el evento ya llegó con `url: null`, así que no hace falta
            reintentar.
          content:
            application/json:
              schema:
                type: object
                required: [error, status]
                properties:
                  error:
                    type: string
                    const: attachment_not_available
                  status:
                    $ref: "#/components/schemas/AttachmentStatus"
              example:
                error: attachment_not_available
                status: failed

  /api/meta/connections:
    get:
      tags: [Connections]
      operationId: listConnections
      summary: Listar las conexiones activas
      description: |
        Devuelve las conexiones **activas** del tenant de la API key (Messenger,
        Instagram y WhatsApp), incluidas las de sus clientes. Las desconectadas
        no aparecen. El `id` es el mismo `page.id` que llega en cada evento del
        webhook y es el que se usa en `PATCH /api/meta/connections/{id}`.

        Una conexión de un canal que la cuenta ya no tiene habilitado se sigue
        listando, pero no se puede editar.
      parameters:
        - name: channel
          in: query
          required: false
          description: Filtra por canal.
          schema:
            type: string
            enum: [messenger, instagram, whatsapp]
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: Las conexiones activas.
          content:
            application/json:
              schema:
                type: object
                required: [connections]
                properties:
                  connections:
                    type: array
                    items:
                      $ref: "#/components/schemas/Connection"
              example:
                connections:
                  - id: 6f1c2d3e-4a5b-4c6d-8e9f-0a1b2c3d4e5f
                    channel: instagram
                    metaPageId: "17841400000000000"
                    name: Tienda
                    username: tienda
                    webhookUrl: https://n8n.example.com/webhook/abc
                    signed: true
                    webhookHeaderNames: [Authorization]
                    paused: false
                  - id: 0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d
                    channel: whatsapp
                    metaPageId: "106540352242922"
                    name: Ventas
                    username: null
                    webhookUrl: null
                    signed: false
                    webhookHeaderNames: []
                    paused: false
                    phoneNumberId: "106540352242922"
                    displayPhoneNumber: "+5491100000000"
                    wabaId: "102290129340398"
        "400":
          description: "`channel` no es uno de los tres canales."
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: channel must be one of messenger, instagram, whatsapp
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: La cuenta está en lista de espera.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: account is on the waitlist
        "429":
          $ref: "#/components/responses/RateLimited"

  /api/meta/connections/{id}:
    patch:
      tags: [Connections]
      operationId: updateConnectionWebhook
      summary: Cambiar el webhook de una conexión
      description: |
        Cambia la URL a la que Pontiun reenvía los eventos entrantes de esa
        conexión. Es lo mismo que guardarla desde `Conexiones`. `null` la
        borra: los eventos se siguen guardando, pero no se reenvían.

        La URL debe ser `https`.

        Si la conexión todavía no tenía secreto de firma, se genera al guardar
        la primera URL y se devuelve **una sola vez** en `signingSecret`. No hay
        forma de volver a leerlo: guardalo en ese momento. Si ya tenía uno, no
        se toca. Rotarlo y pausar el reenvío solo se puede hacer desde la
        consola.

        `webhookHeaders` agrega headers propios a cada `POST` del webhook, para
        receptores que piden su propia credencial (por ejemplo
        `Authorization: Bearer …`) en vez de verificar la firma. Es un objeto
        `{ nombre: valor }` que **reemplaza el conjunto entero**; `null` los
        borra. Hasta 5 por conexión. El valor se guarda cifrado y no se vuelve a
        mostrar: la respuesta trae solo los nombres en `webhookHeaderNames`. No
        se pueden usar `Content-Type`, `resender-*` ni los headers del
        protocolo (`Host`, `Content-Length`, `Connection`, `proxy-*`, `sec-*`…).

        Mandá `webhookUrl`, `webhookHeaders` o los dos. Si algo es inválido no
        se guarda nada.

        No consume cuota y funciona aunque la cuenta tenga los envíos
        restringidos. No necesita `Idempotency-Key`: repetir el mismo `PATCH`
        deja el mismo resultado.
      parameters:
        - name: id
          in: path
          required: true
          description: El `id` de la conexión (`page.id` en los eventos del webhook).
          schema:
            type: string
            format: uuid
        - $ref: "#/components/parameters/RequestId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              minProperties: 1
              properties:
                webhookUrl:
                  description: La URL nueva, o `null` para borrarla.
                  oneOf:
                    - type: string
                      format: uri
                    - type: "null"
                webhookHeaders:
                  description: |
                    Headers propios del webhook, `{ nombre: valor }`, o `null`
                    para borrarlos. Reemplaza el conjunto entero. Valores en
                    ASCII imprimible, sin saltos de línea, hasta 2048
                    caracteres.
                  oneOf:
                    - type: object
                      maxProperties: 5
                      additionalProperties:
                        type: string
                        minLength: 1
                        maxLength: 2048
                    - type: "null"
            examples:
              guardar:
                value: { webhookUrl: https://n8n.example.com/webhook/abc }
              borrar:
                value: { webhookUrl: null }
              conHeader:
                summary: URL + Authorization para el bot
                value:
                  webhookUrl: https://bot.example.com/pontiun
                  webhookHeaders: { Authorization: Bearer bot_7f3c… }
              borrarHeaders:
                value: { webhookHeaders: null }
      responses:
        "200":
          description: Cambios guardados.
          content:
            application/json:
              schema:
                type: object
                required: [connection]
                properties:
                  connection:
                    $ref: "#/components/schemas/Connection"
                  signingSecret:
                    type: string
                    description: |
                      El secreto de firma en claro, presente **solo** cuando se
                      acaba de generar.
              example:
                connection:
                  id: 6f1c2d3e-4a5b-4c6d-8e9f-0a1b2c3d4e5f
                  channel: instagram
                  metaPageId: "17841400000000000"
                  name: Tienda
                  username: tienda
                  webhookUrl: https://n8n.example.com/webhook/abc
                  signed: true
                  webhookHeaderNames: []
                  paused: false
                signingSecret: whsec_3f9a…
        "400":
          description: JSON inválido, faltan `webhookUrl` y `webhookHeaders`, la URL no es válida o algún header no es válido.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                noHttps:
                  value:
                    error: invalid_webhook_url
                    message: webhookUrl must use https
                invalida:
                  value:
                    error: invalid_webhook_url
                    message: webhookUrl is not a valid URL
                headerReservado:
                  value:
                    error: invalid_webhook_headers
                    message: webhookHeaders cannot set Content-Type, resender-* or protocol headers
                demasiadosHeaders:
                  value:
                    error: invalid_webhook_headers
                    message: webhookHeaders accepts at most 5 headers
                faltante:
                  value:
                    error: webhookUrl (a URL or null) or webhookHeaders (an object or null) is required
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: El canal de la conexión no está habilitado, o la cuenta está en lista de espera.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                canal:
                  value:
                    error: channel_not_enabled
                    message: instagram channel is not enabled
                waitlist:
                  value: { error: account is on the waitlist }
        "404":
          description: La conexión no existe, no es de este tenant o está desconectada.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                error: connection not found
        "429":
          $ref: "#/components/responses/RateLimited"

webhooks:
  messengerEvents:
    post:
      tags: [Webhooks]
      operationId: messengerEvents
      summary: Evento de Messenger
      description: |
        Pontiun hace `POST` a la Webhook URL configurada en la conexión
        (debe ser HTTPS) por cada mensaje o postback recibido en la página.
        Las confirmaciones de lectura y entrega no generan eventos.

        Entrega y reintentos: un `2xx` cierra la entrega (el cuerpo se
        ignora). `408`, `429`, `5xx`, timeout (5 s) y errores de red se
        reintentan hasta cinco veces con esperas de 5 s, 30 s, 120 s, 300 s y
        900 s. Cualquier otro `4xx` es definitivo y no se reintenta.

        Orden: los mensajes de una misma conversación se entregan en orden.
        Uno no sale mientras el anterior se esté reintentando; si tu endpoint
        está caído, esa conversación espera y las demás siguen.

        Deduplicá por `resender-event-id`: es estable por evento.

        Headers propios: si tu receptor pide su propia credencial (por ejemplo
        `Authorization: Bearer …`), configurala en la conexión con
        `webhookHeaders` y llega en cada `POST`, junto a los de firma.
      parameters:
        - $ref: "#/components/parameters/ResenderEventId"
        - $ref: "#/components/parameters/ResenderTimestamp"
        - $ref: "#/components/parameters/ResenderSignature"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MessageEvent"
            example:
              type: message
              tenant:
                id: 2b7f2a1c-0d3e-4f5a-9b6c-7d8e9f0a1b2c
              page:
                id: 5c4d3e2f-1a0b-4c9d-8e7f-6a5b4c3d2e1f
                channel: messenger
                metaPageId: "123456789012345"
                name: Tienda Demo
                username: null
              conversation:
                id: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                contactId: "9876543210987654"
              message:
                id: 0c9d2f6e-3b7a-4e1d-8f5c-2a1b3c4d5e6f
                metaMessageId: m_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789
                eventType: message
                postbackPayload: null
                direction: inbound
                status: received
                text: "Hola, ¿tienen talle 38?"
                attachment: null
                createdAt: "2026-09-10T14:03:21.000Z"
      responses:
        "2XX":
          description: Entrega aceptada. El cuerpo se ignora.
        "408":
          description: Se reintenta.
        "429":
          description: Se reintenta.
        "4XX":
          description: Fallo permanente. No se reintenta.
        "5XX":
          description: Se reintenta.
      security:
        - WebhookSignature: []
        - {}

  instagramEvents:
    post:
      tags: [Webhooks]
      operationId: instagramEvents
      summary: Evento de Instagram
      description: |
        Mismo endpoint, cabeceras y política de reintentos que Messenger. El
        campo `type` discrimina dos eventos:

        - `message`: mensaje directo recibido. Hoy solo texto,
          `message.attachment` siempre es `null`.
        - `comment`: comentario nuevo en un post o reel. `comment.igCommentId`
          es el valor que se pasa como `commentId` a los endpoints de
          respuesta.
      parameters:
        - $ref: "#/components/parameters/ResenderEventId"
        - $ref: "#/components/parameters/ResenderTimestamp"
        - $ref: "#/components/parameters/ResenderSignature"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - $ref: "#/components/schemas/MessageEvent"
                - $ref: "#/components/schemas/CommentEvent"
              discriminator:
                propertyName: type
                mapping:
                  message: "#/components/schemas/MessageEvent"
                  comment: "#/components/schemas/CommentEvent"
            examples:
              mensaje:
                summary: Mensaje directo
                value:
                  type: message
                  tenant:
                    id: 2b7f2a1c-0d3e-4f5a-9b6c-7d8e9f0a1b2c
                  page:
                    id: 7a6b5c4d-3e2f-4a1b-9c8d-7e6f5a4b3c2d
                    channel: instagram
                    metaPageId: "17841400000000000"
                    name: Tienda Demo
                    username: tiendademo
                  conversation:
                    id: 9a8b7c6d-5e4f-4a3b-2c1d-0e9f8a7b6c5d
                    contactId: "1234567890123456"
                  message:
                    id: 1b2c3d4e-5f6a-4b7c-8d9e-0f1a2b3c4d5e
                    metaMessageId: aWdfZG1faXRlbToxOklHTWVzc2FnZUlEOjE3ODQxNDAwMDAwMDAwMDAw
                    eventType: message
                    postbackPayload: null
                    direction: inbound
                    status: received
                    text: "Hola, ¿tienen talle 38?"
                    attachment: null
                    createdAt: "2026-09-10T14:03:21.000Z"
              comentario:
                summary: Comentario en un post
                value:
                  type: comment
                  tenant:
                    id: 2b7f2a1c-0d3e-4f5a-9b6c-7d8e9f0a1b2c
                  page:
                    id: 7a6b5c4d-3e2f-4a1b-9c8d-7e6f5a4b3c2d
                    channel: instagram
                    metaPageId: "17841400000000000"
                    name: Tienda Demo
                    username: tiendademo
                  comment:
                    id: 8f1c2d3e-4a5b-4c6d-8e7f-9a0b1c2d3e4f
                    igCommentId: "17900000000000000"
                    parentIgCommentId: null
                    mediaId: "17850000000000000"
                    mediaProductType: FEED
                    from:
                      igId: "1234567890123456"
                      username: cliente_demo
                    direction: inbound
                    status: received
                    text: "¿Precio?"
                    createdAt: "2026-09-10T14:03:21.000Z"
      responses:
        "2XX":
          description: Entrega aceptada. El cuerpo se ignora.
        "408":
          description: Se reintenta.
        "429":
          description: Se reintenta.
        "4XX":
          description: Fallo permanente. No se reintenta.
        "5XX":
          description: Se reintenta.
      security:
        - WebhookSignature: []
        - {}

  whatsappEvents:
    post:
      tags: [Webhooks]
      operationId: whatsappEvents
      summary: Evento de WhatsApp
      description: |
        Mismo endpoint, cabeceras y política de reintentos que Messenger, con
        `page.channel: whatsapp` y los campos propios del canal en `page` y en
        `message`.

        **Adjuntos.** Una imagen, audio, vídeo, documento o sticker se guarda
        en Pontiun y el evento **sale cuando el archivo ya está disponible**:
        llega una sola vez, con `details.status: available` y en
        `attachment.url` un link firmado que se abre sin cabeceras durante
        24 h (`details.urlExpiresAt`). Ver `downloadWhatsappMedia`.
        - Si el archivo no se pudo bajar de WhatsApp, o no estuvo listo en
          2 minutos, el evento sale igual con `details.status: failed` y
          `url: null`. El texto y el resto del mensaje llegan completos.
        - `unavailable` (WhatsApp no ofreció el archivo) y `deleted` también
          llegan con `url: null`.
        - Ubicación, contactos, reacción, respuesta interactiva, pedido y
          evento de sistema no tienen archivo: `url: null` y sin
          `details.status`.
        - El pie de foto es `message.text`.

        **Orden.** Los mensajes de una misma conversación llegan en el orden
        en que se escribieron. Uno no sale mientras el anterior esté
        esperando su archivo o reintentándose. Un mensaje que Meta nos
        entrega tarde, con hora anterior a uno ya enviado, sale apenas llega:
        ordená por `message.createdAt` si necesitás el orden exacto.

        **Ecos.** En Coexistence, lo que el negocio escribe desde la app de
        WhatsApp Business llega con `direction: outbound` y
        `origin: business_app`. Filtralos para que tu bot no se responda a sí
        mismo. El historial importado al conectar no se reenvía.
      parameters:
        - $ref: "#/components/parameters/ResenderEventId"
        - $ref: "#/components/parameters/ResenderTimestamp"
        - $ref: "#/components/parameters/ResenderSignature"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MessageEvent"
            examples:
              imagen:
                summary: Imagen recibida
                value:
                  type: message
                  tenant:
                    id: 299ae9fd-0f88-41c0-9be6-6a77af820f0b
                  page:
                    id: 60c64f0e-00f7-4a05-8ace-ebf55d32de23
                    channel: whatsapp
                    metaPageId: "1323965804140265"
                    name: "+5215639549493"
                    username: null
                    phoneNumberId: "1323965804140265"
                    wabaId: "2186711465527958"
                    onboardingMode: coexistence
                  conversation:
                    id: fbfdf7d2-6c92-4766-893a-459d31b256ba
                    contactId: "5215533397755"
                  message:
                    id: cce03202-3f6d-4379-b85e-6cc11063ccd5
                    metaMessageId: wamid.HBgNNTIxNTUzMzM5Nzc1NRUCABIYFDNBMzg3OTU3NDUyMjc5QTZCNzJDAA==
                    eventType: message
                    postbackPayload: null
                    direction: inbound
                    status: received
                    text: ""
                    attachment:
                      type: image
                      url: https://pontiun.com/api/meta/whatsapp/media/cce03202-3f6d-4379-b85e-6cc11063ccd5?exp=1792526083&sig=1pQ2o3r4S5t6U7v8W9x0Y1z2A3b4C5d6E7f8G9h0I1j
                      title: null
                      details:
                        status: available
                        mimeType: image/jpeg
                        sizeBytes: 32671
                        sha256: 3tMN9VDdwm57MjYO++WdT7Bka/1erTllGtiwLOmoaWs=
                        providerMediaId: "1093987910041490"
                        urlExpiresAt: "2026-10-20T19:54:43.000Z"
                    createdAt: "2026-10-19T19:54:43.000Z"
                    origin: customer
                    historical: false
                    replyToProviderMessageId: null
                    deliveryStatus: null
              adjuntoFallido:
                summary: Adjunto que no se pudo bajar
                value:
                  type: message
                  tenant:
                    id: 299ae9fd-0f88-41c0-9be6-6a77af820f0b
                  page:
                    id: 60c64f0e-00f7-4a05-8ace-ebf55d32de23
                    channel: whatsapp
                    metaPageId: "1323965804140265"
                    name: "+5215639549493"
                    username: null
                    phoneNumberId: "1323965804140265"
                    wabaId: "2186711465527958"
                    onboardingMode: coexistence
                  conversation:
                    id: fbfdf7d2-6c92-4766-893a-459d31b256ba
                    contactId: "5215533397755"
                  message:
                    id: 3d1e7a90-5b2c-4f8e-9a6d-1c0b2e3f4a5b
                    metaMessageId: wamid.HBgNNTIxNTUzMzM5Nzc1NRUCABIYFDNBMzg3OTU3NDUyMjc5QTZCNzJEAA==
                    eventType: message
                    postbackPayload: null
                    direction: inbound
                    status: received
                    text: "Te mando la factura"
                    attachment:
                      type: file
                      url: null
                      title: null
                      details:
                        status: failed
                        failureReason: media_download_timeout
                        mimeType: application/pdf
                        filename: factura.pdf
                        providerMediaId: "1093987910041491"
                    createdAt: "2026-10-19T19:55:10.000Z"
                    origin: customer
                    historical: false
                    replyToProviderMessageId: null
                    deliveryStatus: null
      responses:
        "2XX":
          description: Entrega aceptada. El cuerpo se ignora.
        "408":
          description: Se reintenta.
        "429":
          description: Se reintenta.
        "4XX":
          description: Fallo permanente. No se reintenta.
        "5XX":
          description: Se reintenta.
      security:
        - WebhookSignature: []
        - {}

components:
  securitySchemes:
    ApiKey:
      type: http
      scheme: bearer
      bearerFormat: pk_live_<64 caracteres>
      description: |
        API key opaca del tenant, creada en **Ajustes → API keys**. Una
        key revocada, inexistente o malformada responde `401
        {"error":"unauthorized"}`.
    WebhookSignature:
      type: apiKey
      in: header
      name: resender-signature
      description: |
        Presente solo si la conexión tiene secreto de firma (`whsec_…`).
        `v1=` + HMAC-SHA256 en hex de
        `"<resender-event-id>.<resender-timestamp>.<cuerpo crudo>"`.
        Verificá sobre el cuerpo crudo, en tiempo constante y con una
        tolerancia de ±300 s sobre `resender-timestamp`.

        Si tu receptor no verifica HMAC y pide un header propio (por ejemplo
        `Authorization: Bearer …`), configuralo en la conexión: desde
        `Conexiones` o con `webhookHeaders` en
        `PATCH /api/meta/connections/{id}`. Se manda en cada evento de los tres
        canales, además de las cabeceras de firma.

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: |
        Clave elegida por el cliente (1–200 caracteres). Repetirla devuelve
        `200` con el resultado original y `resender.idempotentReplay: true`,
        sin volver a llamar a Meta. Una cabecera vacía o de más de 200
        caracteres responde `400`.
      schema:
        type: string
        minLength: 1
        maxLength: 200
      example: order-8841-confirmation
    WhatsappIdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: |
        **Obligatoria en WhatsApp.** Clave elegida por el cliente (1–200
        caracteres). Repetirla devuelve `200` con el resultado original y
        `resender.idempotentReplay: true`, sin volver a llamar a Meta ni
        consumir cuota. Ausente, vacía o de más de 200 caracteres responde
        `400`.
      schema:
        type: string
        minLength: 1
        maxLength: 200
      example: order-8841-shipped
    RequestId:
      name: x-request-id
      in: header
      required: false
      description: Identificador de correlación opcional que se copia a los logs del servidor.
      schema:
        type: string
    ResenderEventId:
      name: resender-event-id
      in: header
      required: false
      description: Id determinista del evento. El mismo evento reingerido trae el mismo id; usalo para deduplicar.
      schema:
        type: string
        pattern: "^evt_[0-9a-f]{32}$"
      example: evt_0189a1b2c3d44e5f8a9b0c1d2e3f4a5b
    ResenderTimestamp:
      name: resender-timestamp
      in: header
      required: false
      description: Epoch en segundos del momento de la firma.
      schema:
        type: string
        pattern: "^[0-9]+$"
      example: "1767225600"
    ResenderSignature:
      name: resender-signature
      in: header
      required: false
      description: "`v1=` + HMAC-SHA256 hex. Ver `WebhookSignature`."
      schema:
        type: string
        pattern: "^v1=[0-9a-f]{64}$"

  schemas:
    # ----- Requests -----------------------------------------------------
    SendTarget:
      type: object
      description: |
        Destino del envío. O `conversationId` solo, o `pageId` +
        `recipientId` (opcionalmente con `conversationId`, que debe
        coincidir con el par).
      properties:
        conversationId:
          type: string
          format: uuid
          description: "`conversation.id` del webhook."
        pageId:
          type: string
          description: "`page.metaPageId` de la cuenta conectada."
        recipientId:
          type: string
          description: "`conversation.contactId` del webhook: PSID en Messenger, IGSID en Instagram."
      anyOf:
        - required: [conversationId]
        - required: [pageId, recipientId]

    OutboundAttachment:
      type: object
      description: Adjunto por URL. Meta descarga el archivo desde la URL; Pontiun nunca sube bytes.
      required: [type, url]
      properties:
        type:
          type: string
          enum: [image, video, audio, file]
        url:
          type: string
          format: uri
          maxLength: 4096
          description: URL pública `https` del archivo, sin usuario ni contraseña. Puede ser una URL firmada.

    MessengerSendRequest:
      allOf:
        - $ref: "#/components/schemas/SendTarget"
        - type: object
          description: Exactamente uno de `reply` o `attachment`.
          properties:
            reply:
              type: string
              minLength: 1
              description: Texto del mensaje. Se recorta el espacio en blanco de los extremos.
            attachment:
              oneOf:
                - $ref: "#/components/schemas/OutboundAttachment"
                - type: "null"
          oneOf:
            - required: [reply]
            - required: [attachment]

    InstagramSendRequest:
      allOf:
        - $ref: "#/components/schemas/SendTarget"
        - type: object
          description: Exactamente uno de `reply` o `attachment`.
          properties:
            reply:
              type: string
              minLength: 1
              description: Texto del mensaje. Máximo 1000 bytes UTF-8.
            attachment:
              oneOf:
                - $ref: "#/components/schemas/OutboundAttachment"
                - type: "null"
          oneOf:
            - required: [reply]
            - required: [attachment]

    CommentReplyRequest:
      type: object
      required: [pageId, commentId, reply]
      properties:
        pageId:
          type: string
          description: IG user id de la cuenta profesional conectada (`page.metaPageId` del webhook).
        commentId:
          type: string
          description: Id de Meta del comentario (`comment.igCommentId` del webhook), no el uuid de Pontiun.
        reply:
          type: string
          minLength: 1
          description: |
            Texto de la respuesta. Pública: máximo 2200 caracteres.
            Privada: máximo 1000 bytes UTF-8.

    WhatsappSendTarget:
      type: object
      description: |
        Destino del envío. O `conversationId` solo, o `pageId` +
        `recipientId` (opcionalmente con `conversationId`, que debe
        coincidir con el par).
      properties:
        conversationId:
          type: string
          format: uuid
          description: "`conversation.id` del webhook."
        pageId:
          type: string
          description: "`phone_number_id` del número conectado (`metaPageId` de la conexión)."
        recipientId:
          type: string
          description: |
            Teléfono del contacto en formato internacional con código de país:
            8 a 15 dígitos, con o sin `+`, espacios o guiones. Se normaliza a
            dígitos, igual que el `wa_id`.
          example: "+52 55 1234 5678"
      anyOf:
        - required: [conversationId]
        - required: [pageId, recipientId]

    WhatsappSendRequest:
      allOf:
        - $ref: "#/components/schemas/WhatsappSendTarget"
        - type: object
          description: Exactamente uno de `reply` o `attachment`.
          properties:
            reply:
              type: string
              minLength: 1
              maxLength: 4096
              description: Texto del mensaje. Máximo 4096 caracteres. Se envía sin vista previa de enlaces.
            attachment:
              oneOf:
                - $ref: "#/components/schemas/WhatsappOutboundAttachment"
                - type: "null"
              description: "`image`, `video` y `audio` conservan su tipo; `file` se envía como `document`. Sin `filename`."
          oneOf:
            - required: [reply]
            - required: [attachment]

    WhatsappOutboundAttachment:
      allOf:
        - $ref: "#/components/schemas/OutboundAttachment"
        - type: object
          properties:
            caption:
              type: [string, "null"]
              maxLength: 1024
              description: |
                Pie de foto: el texto que se ve debajo del adjunto, en el mismo
                mensaje. Solo WhatsApp, y solo en `image`, `video` y `file`; en
                `audio` responde `400` con `attachment_caption_unsupported`.
                Máximo 1024 caracteres. Vacío o `null` es "sin pie de foto".
                Se guarda como el texto del mensaje en el historial.
              example: Así quedó tu pedido #8841.

    WhatsappTemplate:
      type: object
      required: [name, language]
      properties:
        name:
          type: string
          minLength: 1
          description: Nombre exacto de la plantilla en WhatsApp Manager.
          example: pedido_enviado
        language:
          type: string
          minLength: 1
          description: Código de idioma de la plantilla.
          example: es_MX
        components:
          type: array
          description: |
            Componentes con los parámetros (`header`, `body`, `button`), en el
            formato de Cloud API. Se reenvían tal cual a Meta; un valor por cada
            variable `{{n}}`, en orden.
          items:
            type: object
            additionalProperties: true

    WhatsappTemplateSendRequest:
      allOf:
        - $ref: "#/components/schemas/WhatsappSendTarget"
        - type: object
          required: [template]
          properties:
            template:
              $ref: "#/components/schemas/WhatsappTemplate"

    WhatsappWindowClosed:
      type: object
      required: [error, requiresTemplate, templateSendingSupported, message]
      properties:
        error:
          type: string
          const: customer_service_window_closed
        requiresTemplate:
          type: boolean
          const: true
        templateSendingSupported:
          type: boolean
          const: true
        message:
          type: string

    WhatsappTemplateNotApproved:
      type: object
      required: [code, error, templateStatus]
      properties:
        code:
          type: string
          const: template_not_approved
        error:
          type: string
        templateStatus:
          type: string
          description: Estado de la plantilla en WhatsApp, por ejemplo `PENDING`, `REJECTED`, `PAUSED` o `DISABLED`.

    WhatsappMetaRejectedMessage:
      description: Meta rechazó el envío. El status HTTP es el que devolvió Cloud API.
      allOf:
        - $ref: "#/components/schemas/MessageSendResponse"
        - type: object
          required: [error]
          properties:
            code:
              type: string
              enum: [attachment_fetch_failed]
              description: Solo cuando Meta no pudo descargar el adjunto (131053).

    # ----- Responses ----------------------------------------------------
    MessageStatus:
      type: string
      enum: [received, sent, failed]

    MessageSendResponse:
      type: object
      required: [meta, resender]
      properties:
        error:
          type: string
          description: Solo cuando el envío falló (replay idempotente de un fallo).
        meta:
          description: Respuesta original de Graph (por ejemplo `message_id`, `recipient_id`).
          oneOf:
            - type: object
              additionalProperties: true
            - type: "null"
        resender:
          type: object
          required: [conversationId, messageId, status]
          properties:
            conversationId:
              type: string
              format: uuid
            messageId:
              type: string
              format: uuid
            status:
              $ref: "#/components/schemas/MessageStatus"
            idempotentReplay:
              type: boolean
              const: true
              description: Presente solo cuando se devolvió un resultado almacenado por `Idempotency-Key`.

    CommentReplyResponse:
      type: object
      required: [resender]
      properties:
        error:
          type: string
          description: Solo cuando la respuesta falló (replay idempotente de un fallo).
        meta:
          description: Respuesta original de Graph (`id` del comentario creado). Ausente en un replay idempotente.
          oneOf:
            - type: object
              additionalProperties: true
            - type: "null"
        resender:
          type: object
          required: [commentId, igCommentId, status]
          properties:
            commentId:
              type: string
              format: uuid
              description: uuid en Pontiun de la respuesta publicada.
            igCommentId:
              oneOf:
                - type: string
                - type: "null"
              description: Id de Meta de la respuesta publicada.
            status:
              $ref: "#/components/schemas/MessageStatus"
            idempotentReplay:
              type: boolean
              const: true

    PrivateReplyConflict:
      type: object
      required: [error, resender]
      properties:
        error:
          type: string
        resender:
          type: object
          required: [conversationId, messageId, status]
          properties:
            conversationId:
              type: string
              format: uuid
            messageId:
              type: string
              format: uuid
            status:
              $ref: "#/components/schemas/MessageStatus"

    Connection:
      type: object
      required: [id, channel, metaPageId, name, username, webhookUrl, signed, webhookHeaderNames, paused]
      properties:
        id:
          type: string
          format: uuid
          description: Id de la conexión. Es el `page.id` de los eventos del webhook.
        channel:
          type: string
          enum: [messenger, instagram, whatsapp]
        metaPageId:
          type: string
          description: Page id (Messenger), IG id (Instagram) o `phone_number_id` (WhatsApp).
        name:
          type: string
        username:
          type: [string, "null"]
          description: El @handle. Solo Instagram; `null` en los otros canales.
        webhookUrl:
          type: [string, "null"]
          format: uri
          description: A dónde se reenvían los eventos. `null` = no se reenvían.
        signed:
          type: boolean
          description: Si la conexión tiene secreto de firma y los eventos salen firmados.
        webhookHeaderNames:
          type: array
          items:
            type: string
          description: |
            Nombres de los headers propios que se mandan en cada `POST` del
            webhook. Los valores nunca se devuelven.
        paused:
          type: boolean
          description: Solo lectura. El reenvío está pausado desde la consola.
        phoneNumberId:
          type: string
          description: Solo WhatsApp.
        displayPhoneNumber:
          type: [string, "null"]
          description: Solo WhatsApp. El número en E.164.
        wabaId:
          type: [string, "null"]
          description: Solo WhatsApp.

    Error:
      type: object
      required: [error]
      properties:
        error:
          type: string
        code:
          type: string
          description: Código estable, presente solo en algunos errores.
        message:
          type: string
          description: Explicación legible, presente en los bloqueos de plan y cuota.
        meta:
          description: Respuesta original de Graph cuando Meta rechazó el envío.
          oneOf:
            - type: object
              additionalProperties: true
            - type: "null"
        resender:
          type: object
          additionalProperties: true

    MetaRejectedMessage:
      description: Meta rechazó el envío. El status HTTP es el que devolvió Graph.
      allOf:
        - $ref: "#/components/schemas/MessageSendResponse"
        - type: object
          required: [error]
          properties:
            code:
              type: string
              enum: [attachment_fetch_failed, attachment_format_rejected]
              description: Solo en Messenger. En Instagram un adjunto rechazado no trae `code`.

    MetaRejectedComment:
      description: Meta rechazó la respuesta. El status HTTP es el que devolvió Graph.
      allOf:
        - $ref: "#/components/schemas/CommentReplyResponse"
        - type: object
          required: [error]

    # ----- Webhook events -----------------------------------------------
    EventPage:
      type: object
      required: [id, channel, metaPageId, name, username]
      properties:
        id:
          type: string
          format: uuid
          description: Id de la conexión en Pontiun.
        channel:
          type: string
          enum: [messenger, instagram, whatsapp]
        metaPageId:
          type: string
          description: Page id en Messenger; IG user id de la cuenta profesional en Instagram; `phone_number_id` en WhatsApp. Es el `pageId` de los endpoints de envío.
        name:
          type: string
        username:
          oneOf:
            - type: string
            - type: "null"
          description: "@handle. Solo Instagram; `null` en Messenger y WhatsApp."
        phoneNumberId:
          type: string
          description: Solo WhatsApp. El mismo valor que `metaPageId`.
        wabaId:
          oneOf: [{ type: string }, { type: "null" }]
          description: Solo WhatsApp. Cuenta de WhatsApp Business del número.
        onboardingMode:
          oneOf:
            - type: string
              enum: [standard, coexistence]
            - type: "null"
          description: Solo WhatsApp. `coexistence` si el número también se usa desde la app de WhatsApp Business.

    InboundAttachment:
      type: object
      required: [type, url, title, details]
      properties:
        type:
          type: string
          enum:
            - image
            - audio
            - video
            - file
            - sticker
            - reel
            - ig_reel
            - post
            - ig_post
            - fallback
            - appointment_booking
            - template
            - unknown
            - location
            - contacts
            - reaction
            - interactive
            - order
            - system
          description: Los seis últimos son solo de WhatsApp.
        url:
          oneOf:
            - type: string
              format: uri
            - type: "null"
          description: |
            Messenger: la URL del CDN de Meta.

            WhatsApp: un link firmado a `GET /api/meta/whatsapp/media/{id}`
            que se abre sin cabeceras hasta `details.urlExpiresAt` (24 h).
            Solo viene con `details.status: available`; con `failed`,
            `unavailable`, `deleted` o un adjunto sin archivo (ubicación,
            contacto, reacción…) es `null`.
        title:
          oneOf:
            - type: string
            - type: "null"
        details:
          type: object
          description: Claves opcionales según el tipo. Un tipo nuevo de Meta entra como `unknown` con `rawType`.
          properties:
            droppedCount:
              type: integer
              description: Adjuntos adicionales del mismo mensaje que no se incluyeron.
            stickerId:
              type: string
            reelVideoId:
              type: string
            postId:
              type: string
            booking:
              type: object
              properties:
                bookingId:
                  type: string
                status:
                  oneOf: [{ type: string }, { type: "null" }]
                startTime:
                  oneOf: [{ type: integer }, { type: "null" }]
                endTime:
                  oneOf: [{ type: integer }, { type: "null" }]
                timezone:
                  oneOf: [{ type: string }, { type: "null" }]
            elements:
              type: array
              items:
                type: object
                additionalProperties: true
            rawType:
              type: string
            raw: {}
            status:
              $ref: "#/components/schemas/AttachmentStatus"
            urlExpiresAt:
              type: string
              format: date-time
              description: Solo WhatsApp. Hasta cuándo se abre `url` sin cabeceras. Después, la misma URL sin `exp`/`sig` sirve con la API key.
            mimeType:
              type: string
              description: Solo WhatsApp. MIME del archivo, por ejemplo `image/jpeg` o `audio/ogg; codecs=opus`.
            sizeBytes:
              type: integer
              description: "Solo WhatsApp, con `status: available`. Tamaño del archivo."
            sha256:
              type: string
              description: Solo WhatsApp. Hash que informa WhatsApp, en base64.
            filename:
              type: string
              description: Solo WhatsApp. Nombre del documento tal como lo mandó el contacto.
            voice:
              type: boolean
              description: Solo WhatsApp, audio. `true` si es una nota de voz.
            animated:
              type: boolean
              description: Solo WhatsApp, sticker.
            providerMediaId:
              type: string
              description: Solo WhatsApp. Id del archivo en Meta. No hace falta para descargarlo.
            failureReason:
              type: string
              description: |
                Solo WhatsApp, con `status: failed`. Por ejemplo
                `media_download_timeout` (no estuvo listo en 2 minutos) o
                `queue_retries_exhausted`. Informativo: no es un catálogo
                cerrado.
          additionalProperties: true

    AttachmentStatus:
      type: string
      enum: [available, failed, deleted, unavailable, pending]
      description: |
        Solo WhatsApp. Estado del archivo del adjunto:

        - `available`: guardado en Pontiun; `url` lo descarga.
        - `failed`: no se pudo bajar de WhatsApp, o no estuvo listo en 2 minutos.
        - `deleted`: pasaron los 180 días de retención.
        - `unavailable`: WhatsApp no ofreció el archivo (historial de más de 14 días).
        - `pending`: todavía bajando. Los eventos ya no salen en este estado;
          solo lo puede devolver la descarga de un mensaje muy reciente.

    MessageEvent:
      type: object
      required: [type, tenant, page, conversation, message]
      properties:
        type:
          type: string
          const: message
        tenant:
          type: object
          required: [id]
          properties:
            id:
              type: string
              format: uuid
        page:
          $ref: "#/components/schemas/EventPage"
        conversation:
          type: object
          required: [id, contactId]
          properties:
            id:
              type: string
              format: uuid
              description: Usable como `conversationId` en los endpoints de envío.
            contactId:
              type: string
              description: PSID (Messenger), IGSID (Instagram) o `wa_id` (WhatsApp) del contacto. Es el `recipientId` de los endpoints de envío.
        message:
          type: object
          required:
            - id
            - metaMessageId
            - eventType
            - postbackPayload
            - direction
            - status
            - text
            - attachment
            - createdAt
          properties:
            id:
              type: string
              format: uuid
            metaMessageId:
              oneOf: [{ type: string }, { type: "null" }]
            eventType:
              type: string
              enum: [message, postback]
            postbackPayload:
              oneOf: [{ type: string }, { type: "null" }]
              description: Payload del botón cuando `eventType` es `postback`.
            direction:
              type: string
              enum: [inbound, outbound]
            status:
              $ref: "#/components/schemas/MessageStatus"
            text:
              type: string
              description: "`\"\"` cuando el mensaje no trajo texto."
            attachment:
              oneOf:
                - $ref: "#/components/schemas/InboundAttachment"
                - type: "null"
              description: Siempre presente; `null` cuando no hubo adjunto. En Instagram es siempre `null` por ahora.
            createdAt:
              type: string
              format: date-time
              description: Hora del mensaje según Meta. Es el orden de la conversación.
            origin:
              type: string
              enum: [customer, resender_api, business_app, history, system]
              description: Solo WhatsApp. Quién produjo el mensaje; `business_app` es un eco escrito desde la app de WhatsApp Business.
            historical:
              type: boolean
              description: Solo WhatsApp. Siempre `false` en el webhook (el historial no se reenvía).
            replyToProviderMessageId:
              oneOf: [{ type: string }, { type: "null" }]
              description: Solo WhatsApp. `wamid` del mensaje al que responde.
            deliveryStatus:
              oneOf:
                - type: string
                  enum: [accepted, sent, delivered, read, failed, deleted]
                - type: "null"
              description: Solo WhatsApp. Estado que reportó Meta para un saliente.

    CommentEvent:
      type: object
      required: [type, tenant, page, comment]
      properties:
        type:
          type: string
          const: comment
        tenant:
          type: object
          required: [id]
          properties:
            id:
              type: string
              format: uuid
        page:
          $ref: "#/components/schemas/EventPage"
        comment:
          type: object
          required:
            - id
            - igCommentId
            - parentIgCommentId
            - mediaId
            - mediaProductType
            - from
            - direction
            - status
            - text
            - createdAt
          properties:
            id:
              type: string
              format: uuid
              description: uuid del comentario en Pontiun.
            igCommentId:
              oneOf: [{ type: string }, { type: "null" }]
              description: Id de Meta. Es el `commentId` de los endpoints de respuesta.
            parentIgCommentId:
              oneOf: [{ type: string }, { type: "null" }]
              description: Informado cuando el comentario responde a otro.
            mediaId:
              type: string
            mediaProductType:
              oneOf: [{ type: string }, { type: "null" }]
              description: Por ejemplo `FEED` o `REELS`.
            from:
              type: object
              required: [igId, username]
              properties:
                igId:
                  type: string
                  description: IGSID de quien comentó.
                username:
                  oneOf: [{ type: string }, { type: "null" }]
            direction:
              type: string
              const: inbound
            status:
              type: string
              const: received
            text:
              type: string
            createdAt:
              type: string
              format: date-time

  responses:
    Unauthorized:
      description: API key ausente, malformada, inexistente o revocada.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: unauthorized

    RateLimited:
      description: Límite por API key excedido. Esperá `Retry-After` segundos.
      headers:
        Retry-After:
          schema:
            type: integer
          description: Segundos a esperar (60).
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: rate_limited

    QuotaExceeded:
      description: Cuota del período agotada. Se resuelve pagando o esperando el próximo período.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: quota_exceeded
            message: You used the 3000 messages of your plan for this billing period. Upgrade your plan to resume sending.

    Forbidden:
      description: |
        La cuenta no puede enviar: en lista de espera, sin suscripción activa,
        plan no disponible o más conexiones de las que el plan permite.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          examples:
            waitlist:
              value: { error: account is on the waitlist }
            sinSuscripcion:
              value: { error: no active subscription }
            plan:
              value:
                error: plan_unavailable
                message: We couldn't resolve your current billing period. Contact support at info@pontiun.com.
            conexiones:
              value:
                error: page_limit_exceeded
                message: Your plan allows 1 connections and you have 2. Disconnect connections in Connections to resume sending.

    ForbiddenInstagram:
      description: |
        Igual que en Messenger, más el caso en que el canal de Instagram no
        está habilitado para la cuenta.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          examples:
            instagram:
              value: { error: instagram channel is not enabled }
            waitlist:
              value: { error: account is on the waitlist }
            sinSuscripcion:
              value: { error: no active subscription }
            plan:
              value:
                error: plan_unavailable
                message: We couldn't resolve your current billing period. Contact support at info@pontiun.com.

    MessengerBadRequest:
      description: Body inválido, destino incompleto, adjunto inválido o `Idempotency-Key` fuera de rango.
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - type: object
                properties:
                  code:
                    type: string
                    enum:
                      - send_destination_missing
                      - send_destination_incomplete
                      - send_target_missing
                      - send_target_conflict
                      - attachment_type_invalid
                      - attachment_url_missing
                      - attachment_url_invalid
                      - conversation_channel_mismatch
          examples:
            json:
              value: { error: invalid json }
            destino:
              value:
                code: send_destination_missing
                error: "missing destination: send conversationId, or pageId and recipientId"
            ambos:
              value:
                code: send_target_conflict
                error: "reply and attachment are mutually exclusive; send exactly one of them"
            adjunto:
              value:
                code: attachment_type_invalid
                error: "attachment.type must be one of image, video, audio, file"
            noCoincide:
              value: { error: conversationId does not match pageId and recipientId }
            canal:
              value:
                code: conversation_channel_mismatch
                error: "conversation belongs to instagram; use /api/meta/instagram/send"
            idempotencia:
              value: { error: Idempotency-Key must be a non-empty string of at most 200 characters }

    InstagramSendBadRequest:
      description: Body inválido, destino incompleto, adjunto inválido, texto demasiado largo o `Idempotency-Key` fuera de rango.
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - type: object
                properties:
                  code:
                    type: string
                    enum:
                      - send_destination_missing
                      - send_destination_incomplete
                      - send_target_missing
                      - send_target_conflict
                      - attachment_type_invalid
                      - attachment_url_missing
                      - attachment_url_invalid
                      - conversation_channel_mismatch
          examples:
            ambos:
              value:
                code: send_target_conflict
                error: "reply and attachment are mutually exclusive; send exactly one of them"
            adjunto:
              value:
                code: attachment_url_invalid
                error: "attachment.url must be an https URL without credentials, at most 4096 characters long"
            largo:
              value:
                error: "reply is too long: Instagram allows 1000 UTF-8 bytes and this message is 1043"
            destino:
              value:
                code: send_destination_missing
                error: "missing destination: send conversationId, or pageId and recipientId"

    CommentBadRequest:
      description: Body inválido, campo faltante, texto de más de 2200 caracteres o `Idempotency-Key` fuera de rango.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          examples:
            faltante:
              value: { error: missing commentId }
            largo:
              value:
                error: "reply is too long: an Instagram comment allows 2200 characters and this reply is 2310"

    PrivateReplyBadRequest:
      description: Body inválido, campo faltante, texto de más de 1000 bytes UTF-8 o `Idempotency-Key` fuera de rango.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          examples:
            faltante:
              value: { error: missing reply }
            largo:
              value:
                error: "reply is too long: Instagram allows 1000 UTF-8 bytes and this message is 1043"

    SendTargetNotFound:
      description: La conversación no existe para este tenant o la cuenta no está conectada.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          examples:
            conversacion:
              value: { error: conversation not found }
            messenger:
              value: { error: Facebook page is not connected for this tenant }
            instagram:
              value: { error: Instagram account is not connected for this tenant }
            whatsapp:
              value: { error: WhatsApp number is not connected for this tenant }

    CommentNotFound:
      description: La cuenta no está conectada o el comentario no llegó por el webhook.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          examples:
            cuenta:
              value: { error: Instagram account is not connected for this tenant }
            comentario:
              value:
                error: "comment not found for this account: Pontiun can only reply to comments it received through the webhook"

    MetaUnreachable:
      description: No se pudo alcanzar la API de Meta (error de red o timeout). Reintentá en breve.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/MetaRejectedMessage"
          example:
            error: "Could not reach Meta's Send API (network error or timeout). Retry shortly."
            meta: null
            resender:
              conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
              messageId: 0c9d2f6e-3b7a-4e1d-8f5c-2a1b3c4d5e6f
              status: failed

    MetaRejectedMessage:
      description: |
        Meta rechazó el envío. El status HTTP es el de Graph (típicamente
        `400`). `error` trae el motivo traducido y `meta` la respuesta
        original. Casos frecuentes: ventana de 24 horas vencida, token
        vencido, adjunto que Meta no pudo descargar.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/MetaRejectedMessage"
          example:
            error: "Messenger's 24-hour window is closed: this contact hasn't messaged the Page in the last 24 hours, so Meta rejects new messages until they write again."
            meta:
              error:
                message: "(#10) This message is sent outside of allowed window."
                type: OAuthException
                code: 10
                error_subcode: 2018278
            resender:
              conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
              messageId: 0c9d2f6e-3b7a-4e1d-8f5c-2a1b3c4d5e6f
              status: failed

    MetaRejectedComment:
      description: Meta rechazó la respuesta. El status HTTP es el de Graph.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/MetaRejectedComment"
          example:
            error: "The Page access token expired or was revoked. Reconnect the Page in Pontiun."
            meta:
              error:
                message: Error validating access token
                type: OAuthException
                code: 190
            resender:
              commentId: 8f1c2d3e-4a5b-4c6d-8e7f-9a0b1c2d3e4f
              igCommentId: null
              status: failed

    ForbiddenWhatsapp:
      description: |
        Igual que en Messenger, más el caso en que el canal de WhatsApp no
        está habilitado para la cuenta.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          examples:
            whatsapp:
              value:
                error: channel_not_enabled
                message: whatsapp channel is not enabled
            waitlist:
              value: { error: account is on the waitlist }
            plan:
              value:
                error: plan_unavailable
                message: We couldn't resolve your current billing period. Contact support at info@pontiun.com.

    WhatsappSendBadRequest:
      description: Body inválido, destino incompleto, teléfono inválido, adjunto inválido, pie de foto inválido, texto demasiado largo o `Idempotency-Key` ausente o fuera de rango.
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - type: object
                properties:
                  code:
                    type: string
                    enum:
                      - send_destination_missing
                      - send_destination_incomplete
                      - send_target_missing
                      - send_target_conflict
                      - attachment_type_invalid
                      - attachment_url_missing
                      - attachment_url_invalid
                      - attachment_caption_invalid
                      - attachment_caption_unsupported
                      - attachment_caption_too_long
                      - conversation_channel_mismatch
                      - invalid_recipient
          examples:
            idempotencia:
              value: { error: Idempotency-Key is required and must be a non-empty string of at most 200 characters }
            destino:
              value:
                code: send_destination_missing
                error: "missing destination: send conversationId, or pageId and recipientId"
            telefono:
              value:
                code: invalid_recipient
                error: 'recipientId must be a phone number in international format (country code included): 8 to 15 digits, with or without "+", spaces or dashes'
            ambos:
              value:
                code: send_target_conflict
                error: "reply and attachment are mutually exclusive; send exactly one of them"
            largo:
              value:
                error: "reply is too long: WhatsApp allows 4096 characters and this message is 4310"
            canal:
              value:
                code: conversation_channel_mismatch
                error: "conversation belongs to messenger; use /api/meta/send"

    WhatsappTemplateBadRequest:
      description: Body inválido, destino incompleto, teléfono inválido, plantilla incompleta o `Idempotency-Key` ausente o fuera de rango.
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - type: object
                properties:
                  code:
                    type: string
                    enum:
                      - send_destination_missing
                      - send_destination_incomplete
                      - conversation_channel_mismatch
                      - invalid_recipient
                      - template_missing
                      - template_name_missing
                      - template_language_missing
                      - template_components_invalid
          examples:
            plantilla:
              value:
                code: template_missing
                error: "missing template: send { name, language, components? }"
            idioma:
              value:
                code: template_language_missing
                error: missing template.language (for example en_US)
            componentes:
              value:
                code: template_components_invalid
                error: template.components must be an array

    WhatsappWindowClosed:
      description: |
        La ventana de atención de 24 horas está cerrada. Pontiun lo resuelve
        sin llamar a Meta y no consume cuota. Enviá una plantilla con
        `POST /api/meta/whatsapp/templates/send` o esperá a que el contacto
        escriba.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/WhatsappWindowClosed"
          example:
            error: customer_service_window_closed
            requiresTemplate: true
            templateSendingSupported: true
            message: "This contact hasn't messaged the number in the last 24 hours, so WhatsApp only accepts approved template messages. Send one with POST /api/meta/whatsapp/templates/send, or wait for the contact to write again."

    WhatsappTemplateNotApproved:
      description: La plantilla existe pero no está `APPROVED`. No se llamó a Meta ni se consumió cuota.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/WhatsappTemplateNotApproved"
          example:
            code: template_not_approved
            error: 'The template "pedido_enviado" (es_MX) is PENDING in WhatsApp, not APPROVED, so it can''t be sent yet.'
            templateStatus: PENDING

    WhatsappUnreachable:
      description: No se pudo alcanzar Cloud API (error de red o timeout). Reintentá con la misma `Idempotency-Key`.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/WhatsappMetaRejectedMessage"
          example:
            error: "Could not reach WhatsApp's Cloud API (network error or timeout). Retry shortly."
            meta: null
            resender:
              conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
              messageId: 0c9d2f6e-3b7a-4e1d-8f5c-2a1b3c4d5e6f
              status: failed

    WhatsappMetaRejected:
      description: |
        Meta rechazó el envío. El status HTTP es el de Cloud API (típicamente
        `400`). `error` trae el motivo traducido y `meta` la respuesta
        original. Casos frecuentes: `131047` ventana cerrada, `131026`
        destinatario sin WhatsApp, `131053` adjunto no descargable
        (`code: attachment_fetch_failed`), `131042` WABA sin método de pago,
        `130429` throughput excedido, `190` token vencido (hay que reconectar
        el número), `132000`/`132001`/`132012`/`132015` errores de plantilla.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/WhatsappMetaRejectedMessage"
          examples:
            parametros:
              value:
                error: "The number of parameters sent doesn't match the variables the template defines. Send one value for each {{n}} variable in the template, in order."
                meta:
                  error:
                    message: "(#132000) Number of parameters does not match the expected number of params"
                    type: OAuthException
                    code: 132000
                resender:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  messageId: 0c9d2f6e-3b7a-4e1d-8f5c-2a1b3c4d5e6f
                  status: failed
            adjunto:
              value:
                code: attachment_fetch_failed
                error: "Meta couldn't download the media from its URL. Make sure the URL is publicly reachable over https, without auth and without broken redirects, and that the file type and size are supported."
                meta:
                  error:
                    message: "(#131053) Media upload error"
                    type: OAuthException
                    code: 131053
                resender:
                  conversationId: 6f0e5a2c-8a5e-4a3d-9c2b-1f2e3d4c5b6a
                  messageId: 0c9d2f6e-3b7a-4e1d-8f5c-2a1b3c4d5e6f
                  status: failed

