{
  "openapi": "3.1.0",
  "info": {
    "title": "WhatsApp Gateway API",
    "description": "Envie e receba mensagens de WhatsApp por números pareados por QR code.\n\n**Autenticação.** As operações recebem uma chave de API (`wag_live_…`), como `Authorization: Bearer <chave>` ou\n`X-Api-Key: <chave>`. Cada operação indica, no requisito de segurança, o escopo de que a chave precisa.\n\n**Erros** respondem `{ \"error\": \"…\" }` com o status HTTP; decida pelo status, não pelo texto.\nUm recurso de outra pessoa responde 404, exatamente como um que não existe.\n\n**Limites.** As requisições têm limite por IP de origem (429 com Retry-After); os envios entram numa fila com ritmo\ncontrolado por número (POST /connections/{id}/send responde 202 com o job).\n\n**Webhooks.** Os eventos são enviados por POST ao webhookBaseUrl do projeto (veja a seção de webhooks), assinados com\nX-Sales-Signature quando o projeto tem um webhookSecret. A entrega é feita pelo menos uma vez.",
    "version": "1.0.0"
  },
  "components": {
    "schemas": {
      "WebhookEventEnvelope": {
        "type": "object",
        "description": "Corpo de todo POST de webhook. Os consumidores devem ignorar os tipos de evento que não conhecem.\n\nCabeçalhos: X-Webhook-Token sempre. Quando o projeto tem um webhookSecret, também\nX-Sales-Timestamp (segundos unix, tomado a cada tentativa de entrega) e\nX-Sales-Signature = \"sha256=\" + hex(HMAC-SHA256(webhookSecret, timestamp + \".\" + rawBody)).\nVerifique sobre os bytes do corpo como recebidos e rejeite um timestamp a mais de 300 s do seu relógio.\n\nA entrega é feita pelo menos uma vez (novas tentativas, reenvios na reconexão): aplique os eventos de forma idempotente, pela chave data.messageId.",
        "properties": {
          "type": {
            "type": "string",
            "enum": [
              "connection.status",
              "message.incoming",
              "message.outgoing",
              "message.delivery",
              "message.send_failed",
              "message.reaction",
              "contact.resolved",
              "group.joined",
              "group.left",
              "group.updated"
            ]
          },
          "connectionId": {
            "type": "string",
            "format": "uuid"
          },
          "tenantId": {
            "type": "string",
            "format": "uuid"
          },
          "externalId": {
            "type": [
              "string",
              "null"
            ]
          },
          "timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "data": {
            "type": "object",
            "additionalProperties": true
          }
        },
        "required": [
          "type",
          "connectionId",
          "tenantId",
          "externalId",
          "timestamp",
          "data"
        ]
      },
      "ConnectionStatusEvent": {
        "type": "object",
        "description": "data de connection.status: o socket abriu ou fechou, ou o WhatsApp mudou o que a conta pode fazer. Um fechamento informado pelo gateway traz o motivo (reason) e se o gateway reconecta sozinho (willReconnect). willReconnect true (transient, restart_required) quer dizer que o gateway continua tentando, com espera crescente, até abrir de novo, o que o próximo status open informa; false quer dizer que ele parou e espera alguém: um QR novo (logged_out, qr_not_scanned) ou uma reconexão explícita (replaced, manual). passkey_required: o QR foi escaneado, mas o pareamento não terminou porque o WhatsApp pediu uma passkey (chave de acesso) ao celular; status é close, não há phoneNumber (a conexão nunca confirmou um) e nenhum QR code novo é gerado até a conexão ser conectada de novo. reachout_timelock: o WhatsApp colocou a conta sob um bloqueio temporário de novas conversas (reach-out timelock; enviado depois de um erro 463 ou de uma notificação do WhatsApp; status é o atual, normalmente open); até reachoutTimelock.endsAt (ou um evento reachout_timelock_lifted), todo envio da fila é descartado como message.send_failed com reason reachout_timelocked, sem ser tentado. reason não vem numa abertura; willReconnect e statusCode só vêm num fechamento com um dos seis primeiros motivos.",
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "connecting",
              "open",
              "close"
            ]
          },
          "phoneNumber": {
            "type": "string",
            "description": "Digits of the paired number, when known; absent with passkey_required."
          },
          "reason": {
            "type": "string",
            "enum": [
              "transient",
              "restart_required",
              "replaced",
              "qr_not_scanned",
              "logged_out",
              "manual",
              "reachout_timelock",
              "reachout_timelock_lifted",
              "passkey_required"
            ],
            "description": "Why the event was sent. On a close: transient, restart_required, replaced, qr_not_scanned, logged_out, manual or passkey_required. The reachout_timelock* reasons come with the current status."
          },
          "willReconnect": {
            "type": "boolean",
            "description": "Only on a close with reason transient, restart_required, replaced, qr_not_scanned, logged_out or manual: whether the gateway reconnects on its own."
          },
          "statusCode": {
            "type": [
              "number",
              "null"
            ],
            "description": "Only with willReconnect. WhatsApp disconnect code (e.g. 401 logged out, 440 replaced, 503 stream error), null when there was none; for diagnostics: branch on reason, not on this."
          },
          "reachoutTimelock": {
            "type": "object",
            "description": "Present with the reachout_timelock* reasons.",
            "properties": {
              "active": {
                "type": "boolean"
              },
              "endsAt": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time",
                "description": "null when WhatsApp gave no end."
              },
              "enforcementType": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "WhatsApp's enforcement type, e.g. DEFAULT or BIZ_QUALITY."
              }
            },
            "required": [
              "active",
              "endsAt",
              "enforcementType"
            ]
          }
        },
        "required": [
          "status"
        ]
      },
      "MessageOutgoingEvent": {
        "type": "object",
        "description": "data de message.outgoing: uma mensagem que o número pareado enviou numa conversa individual. Emitido uma vez por messageId, e só para um projeto criado ou atualizado com emitOutgoing: true (desligado por padrão). origin API = o gateway a enviou por POST /connections/:id/send (o id foi registrado antes do envio, então é uma consulta, nunca um palpite); origin PHONE = digitada no celular ou em outro aparelho conectado. Grupos, status e canais não são informados.",
        "properties": {
          "messageId": {
            "type": "string"
          },
          "origin": {
            "type": "string",
            "enum": [
              "API",
              "PHONE"
            ]
          },
          "clientRef": {
            "type": [
              "string",
              "null"
            ],
            "description": "Echo of the send's clientRef for origin API; always null for PHONE."
          },
          "to": {
            "type": "string",
            "description": "Raw WhatsApp JID of the other party (…@s.whatsapp.net or …@lid). Always present."
          },
          "jid": {
            "type": "string",
            "description": "Raw WhatsApp JID of the other party (…@s.whatsapp.net or …@lid). Always present."
          },
          "toE164": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^\\+[1-9]\\d{7,14}$",
            "description": "Same value as phone."
          },
          "phone": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^\\+[1-9]\\d{7,14}$",
            "description": "E.164 phone of the other party (e.g. \"+5511999999999\"). null when the chat is addressed by a LID the gateway could not resolve (or for group chats). The event is never dropped for that reason."
          },
          "body": {
            "type": "string",
            "description": "Text, or the media caption; empty for media without caption."
          },
          "timestamp": {
            "type": "number",
            "description": "Unix seconds."
          },
          "mediaType": {
            "type": "string",
            "enum": [
              "image",
              "video",
              "audio",
              "document",
              "sticker",
              "location"
            ]
          }
        },
        "required": [
          "messageId",
          "origin",
          "clientRef",
          "to",
          "jid",
          "toE164",
          "phone",
          "body",
          "timestamp"
        ]
      },
      "MessageIncomingEvent": {
        "type": "object",
        "description": "data de message.incoming: uma mensagem que alguém enviou ao número, numa conversa individual ou num grupo de que ele participa (nesse caso, jid é o grupo e phone é null).",
        "properties": {
          "from": {
            "type": "string",
            "description": "Raw sender JID (kept for existing consumers)."
          },
          "jid": {
            "type": "string",
            "description": "Raw WhatsApp JID of the other party (…@s.whatsapp.net or …@lid). Always present."
          },
          "phone": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^\\+[1-9]\\d{7,14}$",
            "description": "E.164 phone of the other party (e.g. \"+5511999999999\"). null when the chat is addressed by a LID the gateway could not resolve (or for group chats). The event is never dropped for that reason."
          },
          "resolvedPhone": {
            "type": "string",
            "description": "Digits only, legacy field; absent when unresolved."
          },
          "to": {
            "type": "string",
            "description": "JID of the paired number, with its linked-device suffix."
          },
          "body": {
            "type": "string",
            "description": "Text, caption or button/list reply; empty for media without caption and locations."
          },
          "timestamp": {
            "type": "number",
            "description": "Unix seconds."
          },
          "media": {
            "type": "object",
            "description": "Present when the message carries media the gateway downloaded.",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "image",
                  "video",
                  "audio",
                  "document",
                  "sticker"
                ]
              },
              "url": {
                "type": "string",
                "format": "uri",
                "description": "Signed, expiring link to the file: <MEDIA_BASE_URL>/media/<connectionId>/<fileName>?exp=<unix seconds>&sig=<base64url>. GET it without credentials, exactly as received, until expiresAt; unsigned, expired or altered it answers 404. It is a bearer credential for this file until then: download the file instead of storing or forwarding the link."
              },
              "mimetype": {
                "type": "string"
              },
              "fileName": {
                "type": "string"
              },
              "fileSize": {
                "type": "number",
                "description": "Bytes."
              },
              "expiresAt": {
                "type": "number",
                "description": "Unix ms when url stops working: its own expiry or the file cleanup, whichever comes first."
              }
            },
            "required": [
              "type",
              "url",
              "mimetype",
              "fileName",
              "fileSize",
              "expiresAt"
            ]
          },
          "location": {
            "type": "object",
            "description": "Present for a location or live-location message.",
            "properties": {
              "latitude": {
                "type": "number"
              },
              "longitude": {
                "type": "number"
              },
              "name": {
                "type": "string"
              },
              "address": {
                "type": "string"
              }
            },
            "required": [
              "latitude",
              "longitude"
            ]
          },
          "raw": {
            "type": "object",
            "additionalProperties": true,
            "description": "The message as WhatsApp Web delivered it (the WebMessageInfo of the pinned Baileys version). Its shape follows WhatsApp, not this contract: prefer the fields above and read raw only for what they do not carry."
          }
        },
        "required": [
          "from",
          "jid",
          "phone",
          "body",
          "timestamp"
        ]
      },
      "MessageDeliveryEvent": {
        "type": "object",
        "description": "data de message.delivery: uma mudança de status de uma mensagem que o número enviou.",
        "properties": {
          "messageId": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "sent",
              "delivered",
              "read",
              "failed"
            ]
          },
          "recipient": {
            "type": "string",
            "description": "Legacy: JID with @s.whatsapp.net stripped (a LID passes through as-is)."
          },
          "jid": {
            "type": "string",
            "description": "Raw WhatsApp JID of the other party (…@s.whatsapp.net or …@lid). Always present."
          },
          "phone": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^\\+[1-9]\\d{7,14}$",
            "description": "E.164 phone of the other party (e.g. \"+5511999999999\"). null when the chat is addressed by a LID the gateway could not resolve (or for group chats). The event is never dropped for that reason."
          },
          "clientRef": {
            "type": [
              "string",
              "null"
            ],
            "description": "The clientRef passed to POST /connections/:id/send for this message; null when none was given or the message was not sent through the API."
          },
          "reason": {
            "type": "string",
            "enum": [
              "reachout_timelocked"
            ],
            "description": "Only with status failed, when WhatsApp said why; absent otherwise. reachout_timelocked: WhatsApp refused the message as a reach-out (ack error 463, typically a contact the number never talked to); it was not delivered and is not retried. Resending makes the restriction worse; see connection.status reason reachout_timelock."
          }
        },
        "required": [
          "messageId",
          "status",
          "recipient",
          "jid",
          "phone",
          "clientRef"
        ]
      },
      "MessageSendFailedEvent": {
        "type": "object",
        "description": "data de message.send_failed: um job enfileirado por POST /connections/:id/send COM um clientRef do qual o gateway desistiu (tentativas esgotadas, a reserva dele expirou na última tentativa, o número não está no WhatsApp, ou a conta está sob um bloqueio temporário de novas conversas do WhatsApp e o envio foi recusado sem ser tentado). Nunca é emitido para um job sem clientRef. Uma nova tentativa com o mesmo clientRef continua respondendo duplicate, então este é o único sinal, para o consumidor, de que o envio aceito não vai acontecer; um reenvio deliberado usa um clientRef novo. Se um eco ou um status de entrega do mesmo clientRef chegar depois, essa prova prevalece.",
        "properties": {
          "clientRef": {
            "type": "string"
          },
          "jobId": {
            "type": "string"
          },
          "messageId": {
            "type": [
              "string",
              "null"
            ],
            "description": "Always null."
          },
          "to": {
            "type": "string",
            "description": "The /send `to` as queued."
          },
          "jid": {
            "type": "string",
            "description": "Raw WhatsApp JID of the other party (…@s.whatsapp.net or …@lid). Always present."
          },
          "phone": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^\\+[1-9]\\d{7,14}$",
            "description": "E.164 phone of the other party (e.g. \"+5511999999999\"). null when the chat is addressed by a LID the gateway could not resolve (or for group chats). The event is never dropped for that reason."
          },
          "reason": {
            "type": "string",
            "enum": [
              "attempts_exhausted",
              "lease_expired",
              "not_on_whatsapp",
              "reachout_timelocked"
            ]
          },
          "attempts": {
            "type": "number"
          }
        },
        "required": [
          "clientRef",
          "jobId",
          "messageId",
          "to",
          "jid",
          "phone",
          "reason",
          "attempts"
        ]
      },
      "ContactResolvedEvent": {
        "type": "object",
        "description": "data de contact.resolved. Um remetente que antes chegou a este projeto como LID, com phone: null, agora tem um número de telefone conhecido. Emitido uma vez por LID pendente por conexão, só para o projeto que recebeu aquelas mensagens. Reatribua todos os eventos anteriores cujo jid seja igual a data.lid.",
        "properties": {
          "lid": {
            "type": "string",
            "description": "The LID JID the earlier events carried, e.g. 123456789012345@lid."
          },
          "jid": {
            "type": "string",
            "description": "Raw WhatsApp JID of the other party (…@s.whatsapp.net or …@lid). Always present."
          },
          "phone": {
            "type": "string",
            "pattern": "^\\+[1-9]\\d{7,14}$",
            "description": "E.164 phone of the other party (e.g. \"+5511999999999\"). null when the chat is addressed by a LID the gateway could not resolve (or for group chats). The event is never dropped for that reason."
          },
          "firstSeenAt": {
            "type": "string",
            "format": "date-time",
            "description": "First message from this LID with no phone."
          },
          "messageCount": {
            "type": "number",
            "description": "Messages received from this LID while it had no phone."
          },
          "source": {
            "type": "string",
            "enum": [
              "lid-mapping",
              "contacts",
              "sweep"
            ]
          }
        },
        "required": [
          "lid",
          "jid",
          "phone",
          "firstSeenAt",
          "messageCount",
          "source"
        ]
      },
      "MessageReactionEvent": {
        "type": "object",
        "description": "data de message.reaction.",
        "properties": {
          "messageId": {
            "type": "string"
          },
          "from": {
            "type": "string",
            "description": "Legacy: JID with @s.whatsapp.net stripped."
          },
          "jid": {
            "type": "string",
            "description": "Raw WhatsApp JID of the other party (…@s.whatsapp.net or …@lid). Always present."
          },
          "phone": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^\\+[1-9]\\d{7,14}$",
            "description": "E.164 phone of the other party (e.g. \"+5511999999999\"). null when the chat is addressed by a LID the gateway could not resolve (or for group chats). The event is never dropped for that reason."
          },
          "emoji": {
            "type": "string",
            "description": "Empty string = reaction removed."
          }
        },
        "required": [
          "messageId",
          "from",
          "jid",
          "phone",
          "emoji"
        ]
      },
      "GroupJoinedEvent": {
        "type": "object",
        "description": "data de group.joined: o número entrou ou foi adicionado a um grupo. Também é enviado uma vez por grupo de que o número já participa quando a conexão dele abre pela primeira vez neste processo do gateway (não de novo nas reconexões).",
        "properties": {
          "groupId": {
            "type": "string",
            "description": "Group JID (…@g.us)."
          },
          "groupName": {
            "type": "string",
            "description": "The group subject; absent when unknown."
          },
          "participantCount": {
            "type": "number",
            "description": "Absent when unknown."
          }
        },
        "required": [
          "groupId"
        ]
      },
      "GroupLeftEvent": {
        "type": "object",
        "description": "data de group.left: o número foi removido de um grupo.",
        "properties": {
          "groupId": {
            "type": "string",
            "description": "Group JID (…@g.us)."
          },
          "reason": {
            "type": "string",
            "enum": [
              "kicked"
            ]
          }
        },
        "required": [
          "groupId",
          "reason"
        ]
      },
      "GroupUpdatedEvent": {
        "type": "object",
        "description": "data de group.updated: um grupo de que o número participa mudou.",
        "properties": {
          "groupId": {
            "type": "string",
            "description": "Group JID (…@g.us)."
          },
          "groupName": {
            "type": "string",
            "description": "The new subject; absent when the update did not change it."
          }
        },
        "required": [
          "groupId"
        ]
      },
      "ErrorResponse": {
        "type": "object",
        "description": "Todo corpo de erro. Decida pelo status HTTP: `error` é uma mensagem para pessoas e pode mudar.",
        "properties": {
          "error": {
            "type": "string"
          },
          "message": {
            "type": "string",
            "description": "Details, on validation errors and rate limits."
          },
          "statusCode": {
            "type": "integer"
          },
          "code": {
            "type": "string",
            "description": "Em erros de validação: FST_ERR_VALIDATION. Em limites do plano: subscription_inactive (402), number_limit_reached (402), plan_feature_required (403)."
          },
          "feature": {
            "type": "string",
            "description": "plan_feature_required: o recurso que o plano da organização não inclui."
          },
          "missingVariables": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "A send with a template: the variables it lacks."
          }
        },
        "required": [
          "error"
        ]
      }
    },
    "parameters": {
      "WebhookToken": {
        "name": "X-Webhook-Token",
        "in": "header",
        "required": true,
        "description": "O webhookToken do projeto (só de escrita em POST e PATCH /tenants). Os webhookHeaders personalizados do projeto também são enviados.",
        "schema": {
          "type": "string"
        }
      },
      "WebhookTimestamp": {
        "name": "X-Sales-Timestamp",
        "in": "header",
        "required": false,
        "description": "Só quando o projeto tem um webhookSecret: segundos unix desta tentativa de entrega (as novas tentativas são assinadas de novo). Rejeite um que esteja a mais de 300 s do seu relógio.",
        "schema": {
          "type": "string",
          "pattern": "^\\d+$"
        },
        "example": "1790251200"
      },
      "WebhookSignature": {
        "name": "X-Sales-Signature",
        "in": "header",
        "required": false,
        "description": "Só quando o projeto tem um webhookSecret: \"sha256=\" + hex(HMAC-SHA256(webhookSecret, X-Sales-Timestamp + \".\" + rawBody)). Calcule sobre os bytes do corpo exatamente como recebidos, nunca sobre um objeto serializado de novo, e compare em tempo constante.",
        "schema": {
          "type": "string",
          "pattern": "^sha256=[0-9a-f]{64}$"
        },
        "example": "sha256=6d1f0c4e9b2a7f3e8c5d1a0b9e8f7a6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a"
      }
    },
    "responses": {
      "BadRequest": {
        "description": "A requisição não segue o schema da operação.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "statusCode": 400,
              "code": "FST_ERR_VALIDATION",
              "error": "Bad Request",
              "message": "body must have required property 'to'"
            }
          }
        }
      },
      "Unauthorized": {
        "description": "Sem chave de API, ou com uma chave inválida (desconhecida, revogada ou expirada).",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "error": "Unauthorized"
            }
          }
        }
      },
      "Forbidden": {
        "description": "A chave de API não tem o escopo do requisito de segurança desta operação, ou o plano da organização não inclui o recurso de que a operação precisa (`code: plan_feature_required`).",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "error": "This credential lacks the messages:send scope"
            }
          }
        }
      },
      "PaymentRequired": {
        "description": "A organização não pode usar o WhatsApp agora: o período de teste acabou, ou uma fatura venceu e passou do prazo de carência (`code: subscription_inactive`). Criar um número além dos contratados: `code: number_limit_reached`.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "error": "The organization cannot use WhatsApp now: its trial ended or an invoice is overdue. Pay to resume",
              "code": "subscription_inactive"
            }
          }
        }
      },
      "NotFound": {
        "description": "Não está entre os recursos de quem chama: o de outra pessoa responde exatamente como um que não existe.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "error": "Not found"
            }
          }
        }
      },
      "TooManyRequests": {
        "description": "Requisições demais deste IP de origem, ou autenticações com falha demais: espere Retry-After segundos.",
        "headers": {
          "Retry-After": {
            "description": "Seconds until the client may try again.",
            "schema": {
              "type": "integer"
            }
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "statusCode": 429,
              "error": "Too Many Requests",
              "message": "Rate limit exceeded, retry in 1 minute"
            }
          }
        }
      },
      "ServiceUnavailable": {
        "description": "A instância do gateway que roda a conexão está mudando (um reinício, um failover) ou não responde: espere Retry-After segundos e tente de novo.",
        "headers": {
          "Retry-After": {
            "description": "Seconds until the client may try again.",
            "schema": {
              "type": "integer"
            }
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "error": "The connection cannot be reached right now: the gateway instance that runs it is changing or does not answer; try again in a few seconds"
            }
          }
        }
      }
    },
    "securitySchemes": {
      "apiKeyBearer": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "wag_live_<prefix>_<secret>",
        "description": "Chave de API como `Authorization: Bearer wag_live_…`."
      },
      "apiKeyHeader": {
        "type": "apiKey",
        "name": "X-Api-Key",
        "in": "header",
        "description": "Chave de API como `X-Api-Key: wag_live_…`."
      }
    }
  },
  "paths": {
    "/me": {
      "get": {
        "operationId": "getCaller",
        "summary": "Quem está chamando",
        "tags": [
          "Account"
        ],
        "description": "A credencial com que esta requisição se autenticou: o tipo, a organização, os escopos que ela tem e os projetos (tenants) a que está vinculada. Uma chave de API alcança só os `tenantIds`; um usuário do painel (`kind: user`, conectado com o cookie de sessão do painel) alcança todos os projetos da organização e das organizações filhas dela, com os escopos do papel do usuário.",
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The calling credential.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The calling credential.",
                  "type": "object",
                  "properties": {
                    "kind": {
                      "type": "string",
                      "enum": [
                        "apiKey",
                        "user",
                        "platform"
                      ],
                      "description": "`platform`: the operator"
                    },
                    "user": {
                      "type": [
                        "object",
                        "null"
                      ],
                      "description": "The signed-in user; null for an API key",
                      "properties": {
                        "id": {
                          "type": "string",
                          "format": "uuid"
                        },
                        "email": {
                          "type": "string",
                          "format": "email"
                        },
                        "name": {
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "email",
                        "name"
                      ]
                    },
                    "organization": {
                      "type": [
                        "object",
                        "null"
                      ],
                      "description": "The organization the credential acts for: the key's tenant's, or the user's current one",
                      "properties": {
                        "id": {
                          "type": "string",
                          "format": "uuid"
                        },
                        "name": {
                          "type": "string"
                        },
                        "slug": {
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "name",
                        "slug"
                      ]
                    },
                    "role": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "enum": [
                        "owner",
                        "admin",
                        "member",
                        null
                      ],
                      "description": "A user's role in the organization"
                    },
                    "scopes": {
                      "type": "array",
                      "items": {
                        "type": "string",
                        "enum": [
                          "connections:read",
                          "connections:write",
                          "messages:send",
                          "templates:write",
                          "webhooks:write",
                          "logs:read",
                          "usage:read",
                          "keys:read",
                          "keys:write",
                          "billing:write",
                          "projects:write"
                        ]
                      }
                    },
                    "tenantIds": {
                      "type": [
                        "array",
                        "null"
                      ],
                      "items": {
                        "type": "string",
                        "format": "uuid"
                      },
                      "description": "The tenants an API key is pinned to; null: every tenant of the organization's"
                    },
                    "apiKey": {
                      "type": [
                        "object",
                        "null"
                      ],
                      "properties": {
                        "id": {
                          "type": "string",
                          "format": "uuid"
                        },
                        "expiresAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time"
                        }
                      },
                      "required": [
                        "id",
                        "expiresAt"
                      ]
                    }
                  },
                  "required": [
                    "kind",
                    "user",
                    "organization",
                    "role",
                    "scopes",
                    "tenantIds",
                    "apiKey"
                  ]
                },
                "examples": {
                  "example1": {
                    "value": {
                      "kind": "apiKey",
                      "user": null,
                      "organization": {
                        "id": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                        "name": "Acme",
                        "slug": "acme"
                      },
                      "role": null,
                      "scopes": [
                        "connections:read",
                        "messages:send"
                      ],
                      "tenantIds": [
                        "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61"
                      ],
                      "apiKey": {
                        "id": "5e8f1a2b-3c4d-4e5f-8a9b-0c1d2e3f4a5b",
                        "expiresAt": null
                      }
                    }
                  },
                  "example2": {
                    "value": {
                      "kind": "user",
                      "user": {
                        "id": "b4c5d6e7-f8a9-4b0c-9d1e-2f3a4b5c6d7e",
                        "email": "ana@acme.example",
                        "name": "Ana"
                      },
                      "organization": {
                        "id": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                        "name": "Acme",
                        "slug": "acme"
                      },
                      "role": "member",
                      "scopes": [
                        "connections:read",
                        "connections:write",
                        "messages:send",
                        "templates:write",
                        "webhooks:write",
                        "logs:read",
                        "usage:read",
                        "keys:read"
                      ],
                      "tenantIds": null,
                      "apiKey": null
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/tenants": {
      "get": {
        "operationId": "listTenants",
        "summary": "Listar projetos",
        "tags": [
          "Tenants"
        ],
        "description": "Os projetos (tenants) de quem chama (todos, para a plataforma), com o plano da organização e o número de conexões.",
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The caller's tenants, newest first.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The caller's tenants, newest first.",
                  "type": "object",
                  "properties": {
                    "tenants": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string",
                            "format": "uuid"
                          },
                          "organizationId": {
                            "type": "string",
                            "format": "uuid",
                            "description": "The organization (customer account) that owns the tenant"
                          },
                          "name": {
                            "type": "string"
                          },
                          "webhookBaseUrl": {
                            "type": "string",
                            "format": "uri"
                          },
                          "webhookHeaderNames": {
                            "type": "array",
                            "items": {
                              "type": "string"
                            },
                            "description": "Names of the custom headers sent with every delivery; their values are write-only"
                          },
                          "emitOutgoing": {
                            "type": "boolean"
                          },
                          "maxPerMinute": {
                            "type": [
                              "number",
                              "null"
                            ]
                          },
                          "maxPerHour": {
                            "type": [
                              "number",
                              "null"
                            ]
                          },
                          "maxPerDay": {
                            "type": [
                              "number",
                              "null"
                            ]
                          },
                          "hasWebhookSecret": {
                            "type": "boolean"
                          },
                          "planId": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "The organization's plan"
                          },
                          "subscriptionStatus": {
                            "type": "string",
                            "description": "The organization's subscription"
                          },
                          "trialEndsAt": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time"
                          },
                          "currentPeriodEnd": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time"
                          },
                          "isActive": {
                            "type": "boolean"
                          },
                          "createdAt": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "updatedAt": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "plan": {
                            "type": [
                              "object",
                              "null"
                            ],
                            "properties": {
                              "id": {
                                "type": "string"
                              },
                              "name": {
                                "type": "string"
                              },
                              "displayName": {
                                "type": "string"
                              },
                              "maxConnections": {
                                "type": "number",
                                "description": "-1 = unlimited"
                              },
                              "maxMessagesDay": {
                                "type": "number",
                                "description": "-1 = unlimited"
                              },
                              "maxMessagesMonth": {
                                "type": "number",
                                "description": "-1 = unlimited"
                              },
                              "monthlyPriceCents": {
                                "type": "number",
                                "description": "-1 = custom"
                              }
                            }
                          },
                          "connectionCount": {
                            "type": "number"
                          }
                        }
                      }
                    },
                    "count": {
                      "type": "number"
                    }
                  }
                },
                "example": {
                  "tenants": [
                    {
                      "id": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                      "organizationId": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                      "name": "acme-crm",
                      "webhookBaseUrl": "https://crm.example.com/api/whatsapp/events",
                      "webhookHeaderNames": [
                        "X-Crm-Account"
                      ],
                      "emitOutgoing": true,
                      "maxPerMinute": null,
                      "maxPerHour": null,
                      "maxPerDay": null,
                      "hasWebhookSecret": true,
                      "planId": "b7e2c9d4-1f3a-4c5b-8d6e-9f0a1b2c3d4e",
                      "subscriptionStatus": "active",
                      "trialEndsAt": null,
                      "currentPeriodEnd": "2026-10-24T12:00:00.000Z",
                      "isActive": true,
                      "createdAt": "2026-09-01T12:00:00.000Z",
                      "updatedAt": "2026-09-24T12:00:00.000Z",
                      "plan": {
                        "id": "b7e2c9d4-1f3a-4c5b-8d6e-9f0a1b2c3d4e",
                        "name": "pro",
                        "displayName": "Pro",
                        "maxConnections": 5,
                        "maxMessagesDay": 1000,
                        "maxMessagesMonth": 20000,
                        "monthlyPriceCents": 9900
                      },
                      "connectionCount": 1
                    }
                  ],
                  "count": 1
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/tenants/webhook-test": {
      "post": {
        "operationId": "testWebhook",
        "summary": "Testar um endpoint de webhook",
        "tags": [
          "Tenants"
        ],
        "description": "Envia um evento `ping` assinado ao endpoint informado, com os mesmos cabeçalhos, assinatura, limite de 10 s e regras de URL das entregas reais (redirecionamentos não são seguidos; um host que resolve para um endereço não público é recusado na conexão). Nada é salvo. Com tenantId, o projeto precisa ser seu.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "webhookBaseUrl": {
                    "type": "string",
                    "description": "URL to POST the ping to; same rules as a tenant webhookBaseUrl"
                  },
                  "webhookToken": {
                    "type": "string",
                    "description": "Omitted: the tenant's stored token, only when webhookBaseUrl is the tenant's saved URL"
                  },
                  "webhookHeaders": {
                    "type": [
                      "object",
                      "null"
                    ],
                    "additionalProperties": {
                      "type": "string"
                    },
                    "description": "Omitted: the tenant's stored headers, only when webhookBaseUrl is the tenant's saved URL"
                  },
                  "webhookSecret": {
                    "type": [
                      "string",
                      "null"
                    ]
                  },
                  "tenantId": {
                    "type": "string",
                    "format": "uuid",
                    "description": "Sign with this tenant's stored secret when webhookSecret is omitted"
                  }
                },
                "required": [
                  "webhookBaseUrl"
                ]
              },
              "example": {
                "webhookBaseUrl": "https://crm.example.com/hooks/whatsapp",
                "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61"
              }
            }
          }
        },
        "security": [
          {
            "apiKeyBearer": [
              "webhooks:write"
            ]
          },
          {
            "apiKeyHeader": [
              "webhooks:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "What the endpoint answered to the ping; nothing is saved.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "What the endpoint answered to the ping; nothing is saved.",
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    },
                    "status": {
                      "type": [
                        "number",
                        "null"
                      ],
                      "description": "HTTP status; null when no response came back"
                    },
                    "latencyMs": {
                      "type": "number"
                    },
                    "error": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "\"timeout\" when the 10s limit fired"
                    }
                  }
                },
                "example": {
                  "ok": true,
                  "status": 200,
                  "latencyMs": 184,
                  "error": null
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/tenants/{id}": {
      "get": {
        "operationId": "getTenant",
        "summary": "Consultar um projeto",
        "tags": [
          "Tenants"
        ],
        "description": "Os detalhes do projeto, com o número de conexões.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The tenant.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The tenant.",
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "organizationId": {
                      "type": "string",
                      "format": "uuid",
                      "description": "The organization (customer account) that owns the tenant"
                    },
                    "name": {
                      "type": "string"
                    },
                    "webhookBaseUrl": {
                      "type": "string",
                      "format": "uri"
                    },
                    "webhookHeaderNames": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      },
                      "description": "Names of the custom headers sent with every delivery; their values are write-only"
                    },
                    "emitOutgoing": {
                      "type": "boolean"
                    },
                    "maxPerMinute": {
                      "type": [
                        "number",
                        "null"
                      ]
                    },
                    "maxPerHour": {
                      "type": [
                        "number",
                        "null"
                      ]
                    },
                    "maxPerDay": {
                      "type": [
                        "number",
                        "null"
                      ]
                    },
                    "hasWebhookSecret": {
                      "type": "boolean"
                    },
                    "planId": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The organization's plan"
                    },
                    "subscriptionStatus": {
                      "type": "string",
                      "description": "The organization's subscription"
                    },
                    "trialEndsAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "currentPeriodEnd": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "isActive": {
                      "type": "boolean"
                    },
                    "createdAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "updatedAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "connectionCount": {
                      "type": "number"
                    }
                  }
                },
                "example": {
                  "id": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                  "organizationId": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                  "name": "acme-crm",
                  "webhookBaseUrl": "https://crm.example.com/api/whatsapp/events",
                  "webhookHeaderNames": [
                    "X-Crm-Account"
                  ],
                  "emitOutgoing": true,
                  "maxPerMinute": null,
                  "maxPerHour": null,
                  "maxPerDay": null,
                  "hasWebhookSecret": true,
                  "planId": "b7e2c9d4-1f3a-4c5b-8d6e-9f0a1b2c3d4e",
                  "subscriptionStatus": "active",
                  "trialEndsAt": null,
                  "currentPeriodEnd": "2026-10-24T12:00:00.000Z",
                  "isActive": true,
                  "createdAt": "2026-09-01T12:00:00.000Z",
                  "updatedAt": "2026-09-24T12:00:00.000Z",
                  "connectionCount": 1
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      },
      "patch": {
        "operationId": "updateTenant",
        "summary": "Atualizar um projeto",
        "tags": [
          "Tenants"
        ],
        "description": "Atualiza a configuração de webhook ou os limites de envio do projeto. O 409 também responde a uma requisição de navegador da mesma origem que altera webhookToken ou webhookHeaders sem X-Admin-Client: um painel desatualizado que os sobrescreveria. name, webhookBaseUrl, planId, isActive e os limites maxPer* são só da plataforma (403 para uma credencial de organização).",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string"
                  },
                  "webhookBaseUrl": {
                    "type": "string",
                    "format": "uri",
                    "description": "Same rules as on create; checked only when it changes."
                  },
                  "webhookToken": {
                    "type": "string",
                    "description": "Write-only: never returned."
                  },
                  "webhookHeaders": {
                    "type": [
                      "object",
                      "null"
                    ],
                    "additionalProperties": {
                      "type": "string"
                    },
                    "description": "Replaces the custom headers; null removes them. Write-only: only their names are returned."
                  },
                  "webhookSecret": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "description": "Signing secret for deliveries; null or \"\" turns signing off. Write-only: never returned."
                  },
                  "emitOutgoing": {
                    "type": "boolean",
                    "description": "Opt-in to message.outgoing events."
                  },
                  "maxPerMinute": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "maxPerHour": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "maxPerDay": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "isActive": {
                    "type": "boolean"
                  },
                  "planId": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "description": "Plan to assign to the tenant's organization (billing is per organization: every tenant of it moves); null removes it. Must exist."
                  }
                }
              },
              "example": {
                "emitOutgoing": true
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "webhooks:write"
            ]
          },
          {
            "apiKeyHeader": [
              "webhooks:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The updated tenant.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "organizationId": {
                      "type": "string",
                      "format": "uuid",
                      "description": "The organization (customer account) that owns the tenant"
                    },
                    "name": {
                      "type": "string"
                    },
                    "webhookBaseUrl": {
                      "type": "string",
                      "format": "uri"
                    },
                    "webhookHeaderNames": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      },
                      "description": "Names of the custom headers sent with every delivery; their values are write-only"
                    },
                    "emitOutgoing": {
                      "type": "boolean"
                    },
                    "maxPerMinute": {
                      "type": [
                        "number",
                        "null"
                      ]
                    },
                    "maxPerHour": {
                      "type": [
                        "number",
                        "null"
                      ]
                    },
                    "maxPerDay": {
                      "type": [
                        "number",
                        "null"
                      ]
                    },
                    "hasWebhookSecret": {
                      "type": "boolean"
                    },
                    "planId": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The organization's plan"
                    },
                    "subscriptionStatus": {
                      "type": "string",
                      "description": "The organization's subscription"
                    },
                    "trialEndsAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "currentPeriodEnd": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "isActive": {
                      "type": "boolean"
                    },
                    "createdAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "updatedAt": {
                      "type": "string",
                      "format": "date-time"
                    }
                  },
                  "description": "The updated tenant."
                },
                "example": {
                  "id": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                  "organizationId": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                  "name": "acme-crm",
                  "webhookBaseUrl": "https://crm.example.com/api/whatsapp/events",
                  "webhookHeaderNames": [
                    "X-Crm-Account"
                  ],
                  "emitOutgoing": true,
                  "maxPerMinute": null,
                  "maxPerHour": null,
                  "maxPerDay": null,
                  "hasWebhookSecret": true,
                  "planId": "b7e2c9d4-1f3a-4c5b-8d6e-9f0a1b2c3d4e",
                  "subscriptionStatus": "active",
                  "trialEndsAt": null,
                  "currentPeriodEnd": "2026-10-24T12:00:00.000Z",
                  "isActive": true,
                  "createdAt": "2026-09-01T12:00:00.000Z",
                  "updatedAt": "2026-09-24T12:00:00.000Z"
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "409": {
            "description": "Conflict",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      },
      "delete": {
        "operationId": "deleteTenant",
        "summary": "Desativar um projeto",
        "tags": [
          "Tenants"
        ],
        "description": "Desativa o projeto e todas as conexões dele: elas são desconectadas, com as sessões preservadas.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Deleted.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Deleted.",
                  "type": "object",
                  "properties": {
                    "deleted": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "deleted": true
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/tenants/{id}/connections": {
      "get": {
        "operationId": "listTenantConnections",
        "summary": "Listar as conexões de um projeto",
        "tags": [
          "Tenants"
        ],
        "description": "Todas as conexões do projeto, com o status gravado.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The tenant's connections, newest first.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The tenant's connections, newest first.",
                  "type": "object",
                  "properties": {
                    "connections": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string",
                            "format": "uuid"
                          },
                          "tenantId": {
                            "type": "string",
                            "format": "uuid"
                          },
                          "tenantName": {
                            "type": "string"
                          },
                          "externalId": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "status": {
                            "type": "string",
                            "enum": [
                              "PENDING",
                              "CONNECTING",
                              "OPEN",
                              "CLOSE",
                              "FAILED",
                              "PASSKEY_REQUIRED"
                            ]
                          },
                          "phoneNumber": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "lastHeartbeat": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time"
                          },
                          "lastConnectedAt": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time"
                          },
                          "createdAt": {
                            "type": "string",
                            "format": "date-time"
                          }
                        }
                      }
                    },
                    "count": {
                      "type": "number"
                    }
                  }
                },
                "example": {
                  "connections": [
                    {
                      "id": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                      "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                      "tenantName": "acme-crm",
                      "externalId": "shop-42",
                      "status": "OPEN",
                      "phoneNumber": "5511900000001",
                      "lastHeartbeat": "2026-09-24T12:00:00.000Z",
                      "lastConnectedAt": "2026-09-24T08:00:00.000Z",
                      "createdAt": "2026-09-01T12:00:00.000Z"
                    }
                  ],
                  "count": 1
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      },
      "post": {
        "operationId": "createTenantConnection",
        "summary": "Criar uma conexão no projeto",
        "tags": [
          "Tenants"
        ],
        "description": "Como POST /connections, para o projeto do caminho: cria uma conexão de WhatsApp (ou conecta a que o externalId indica) e a devolve como GET /tenants/{id}/connections a lista. Cada conexão ocupa um dos números que a organização do projeto contratou até ser apagada: além deles, 402 `number_limit_reached`.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": [
                  "object",
                  "null"
                ],
                "properties": {
                  "externalId": {
                    "type": "string",
                    "description": "Optional tenant-specific identifier (e.g., businessId)"
                  },
                  "proxy": {
                    "type": [
                      "object",
                      "null"
                    ],
                    "required": [
                      "url"
                    ],
                    "additionalProperties": false,
                    "properties": {
                      "url": {
                        "type": "string",
                        "minLength": 1,
                        "maxLength": 2048,
                        "description": "socks5://, socks5h:// (the proxy resolves hostnames in both), http:// or https:// (HTTP CONNECT), with optional user:password@. Write-only."
                      },
                      "country": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "pattern": "^[A-Za-z]{2}$",
                        "description": "The country the proxy must exit from (ISO 3166-1 alpha-2, e.g. BR); omitted or null: any"
                      }
                    },
                    "description": "The connection's own proxy, as PUT /connections/{id}/proxy takes it",
                    "example": {
                      "url": "socks5://user:password@br.proxy.example.com:1080",
                      "country": "BR"
                    }
                  }
                }
              },
              "example": {
                "externalId": "shop-42"
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The connection, pending until it is paired.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The connection, pending until it is paired.",
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "tenantId": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "externalId": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "status": {
                      "type": "string"
                    },
                    "phoneNumber": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "lastHeartbeat": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "lastConnectedAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "createdAt": {
                      "type": "string",
                      "format": "date-time"
                    }
                  }
                },
                "example": {
                  "id": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                  "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                  "externalId": "shop-42",
                  "status": "pending",
                  "phoneNumber": null,
                  "lastHeartbeat": null,
                  "lastConnectedAt": null,
                  "createdAt": "2026-09-24T12:00:00.000Z"
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "422": {
            "description": "The check through the proxy failed: nothing was created.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The check through the proxy failed: nothing was created."
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "error": "Connection created but not persisted"
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "description": "This gateway cannot store proxy URLs: no encryption key is configured.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "This gateway cannot store proxy URLs: no encryption key is configured."
                }
              }
            }
          }
        }
      }
    },
    "/tenants/{id}/connections/{connId}": {
      "get": {
        "operationId": "getTenantConnection",
        "summary": "Consultar uma conexão",
        "tags": [
          "Tenants"
        ],
        "description": "Os detalhes da conexão, com os 50 eventos mais recentes (exceto os heartbeats bem-sucedidos).",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "connId",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The connection and its recent events, newest first.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The connection and its recent events, newest first.",
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "tenantId": {
                      "type": "string"
                    },
                    "externalId": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "status": {
                      "type": "string"
                    },
                    "phoneNumber": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "lastHeartbeat": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "lastConnectedAt": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "createdAt": {
                      "type": "string"
                    },
                    "events": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string"
                          },
                          "eventType": {
                            "type": "string"
                          },
                          "details": {
                            "type": [
                              "object",
                              "null"
                            ]
                          },
                          "createdAt": {
                            "type": "string"
                          }
                        }
                      }
                    }
                  }
                },
                "example": {
                  "id": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                  "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                  "externalId": "shop-42",
                  "status": "open",
                  "phoneNumber": "5511900000001",
                  "lastHeartbeat": "2026-09-24T12:00:00.000Z",
                  "lastConnectedAt": "2026-09-24T08:00:00.000Z",
                  "createdAt": "2026-09-01T12:00:00.000Z",
                  "events": [
                    {
                      "id": "e4f5a6b7-c8d9-4e0f-8a1b-2c3d4e5f6a7b",
                      "eventType": "CONNECTED",
                      "details": {
                        "phoneNumber": "5511900000001"
                      },
                      "createdAt": "2026-09-24T08:00:00.000Z"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      },
      "delete": {
        "operationId": "deleteTenantConnection",
        "summary": "Excluir uma conexão",
        "tags": [
          "Tenants"
        ],
        "description": "Desconecta o número (o aparelho conectado sai do celular) e exclui a conexão com a sessão, os templates e o histórico. Não pode ser desfeito. Quando não é possível desconectar o número, nada é excluído: responde 409, tente de novo.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "connId",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Done.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Done.",
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "ok": true
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "409": {
            "description": "Conflict",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/tenants/{id}/connections/{connId}/heartbeats": {
      "get": {
        "operationId": "getConnectionHeartbeats",
        "summary": "Histórico de heartbeats da conexão",
        "tags": [
          "Tenants"
        ],
        "description": "Intervalos de meia hora, do mais antigo ao mais recente (o último é o atual, parcial). ok=false quando um heartbeat falhou no intervalo, true quando um teve sucesso, null sem dados.",
        "parameters": [
          {
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 168,
              "default": 24
            },
            "in": "query",
            "name": "hours",
            "required": false
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "connId",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The uptime history.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The uptime history.",
                  "type": "object",
                  "properties": {
                    "buckets": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "start": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "ok": {
                            "type": [
                              "boolean",
                              "null"
                            ]
                          }
                        }
                      }
                    },
                    "uptimePct": {
                      "type": [
                        "number",
                        "null"
                      ]
                    }
                  }
                },
                "example": {
                  "buckets": [
                    {
                      "start": "2026-09-24T11:00:00.000Z",
                      "ok": true
                    },
                    {
                      "start": "2026-09-24T11:30:00.000Z",
                      "ok": false
                    },
                    {
                      "start": "2026-09-24T12:00:00.000Z",
                      "ok": null
                    }
                  ],
                  "uptimePct": 50
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/tenants/{id}/connections/{connId}/qr": {
      "get": {
        "operationId": "getTenantConnectionQr",
        "summary": "Obter o QR code como imagem",
        "tags": [
          "Tenants"
        ],
        "description": "Como GET /connections/{id}/qr, com o QR code já renderizado como data URL PNG, pronto para usar como fonte de uma imagem, e também só para quem tem o escopo connections:write (null para os demais). status é o atual ou, sem ele, o gravado (em minúsculas).",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "connId",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The QR code image while pairing, and the status.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The QR code image while pairing, and the status.",
                  "type": "object",
                  "properties": {
                    "qrCode": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "PNG data URL; null when there is no QR code to scan, or the caller lacks connections:write"
                    },
                    "status": {
                      "type": "string"
                    }
                  }
                },
                "example": {
                  "qrCode": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
                  "status": "connecting"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/tenants/{id}/connections/{connId}/disconnect": {
      "post": {
        "operationId": "disconnectTenantConnection",
        "summary": "Desconectar uma conexão",
        "tags": [
          "Tenants"
        ],
        "description": "Como POST /connections/{id}/disconnect: fecha o socket e preserva a sessão.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "connId",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Done.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Done.",
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "ok": true
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/tenants/{id}/connections/{connId}/connect": {
      "post": {
        "operationId": "reconnectTenantConnection",
        "summary": "Conectar de novo uma conexão",
        "tags": [
          "Tenants"
        ],
        "description": "Inicia o socket de uma conexão fechada: com sessão, ela reconecta; sem sessão, começa o pareamento e GET /connections/{id}/qr mostra o QR code.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "connId",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Done.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Done.",
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "ok": true
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/tenants/{id}/api-keys": {
      "get": {
        "operationId": "listApiKeys",
        "summary": "Listar as chaves de API de um projeto",
        "tags": [
          "API keys"
        ],
        "description": "As chaves do projeto, das mais novas para as mais antigas: todas as que ainda funcionam e as 100 revogadas ou expiradas mais recentes. Nunca as chaves em si.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "keys:read"
            ]
          },
          {
            "apiKeyHeader": [
              "keys:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The tenant's keys, newest first.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The tenant's keys, newest first.",
                  "type": "object",
                  "properties": {
                    "apiKeys": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string",
                            "format": "uuid"
                          },
                          "tenantId": {
                            "type": "string",
                            "format": "uuid"
                          },
                          "organizationId": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "The tenant's organization"
                          },
                          "name": {
                            "type": "string"
                          },
                          "prefix": {
                            "type": "string",
                            "description": "Identifies the key; not secret"
                          },
                          "maskedKey": {
                            "type": "string",
                            "description": "wag_live_<prefix>_…, to recognise the key"
                          },
                          "scopes": {
                            "type": "array",
                            "items": {
                              "type": "string",
                              "enum": [
                                "connections:read",
                                "connections:write",
                                "messages:send",
                                "templates:write",
                                "webhooks:write",
                                "logs:read",
                                "usage:read",
                                "keys:read",
                                "keys:write"
                              ]
                            }
                          },
                          "status": {
                            "type": "string",
                            "enum": [
                              "active",
                              "expired",
                              "revoked"
                            ]
                          },
                          "createdBy": {
                            "type": "string",
                            "description": "\"apiKey:<id>\" of the key that created it, \"user:<id>\" of the dashboard user, or \"platform\""
                          },
                          "createdAt": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "lastUsedAt": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time",
                            "description": "Updated at most once a minute"
                          },
                          "expiresAt": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time"
                          },
                          "revokedAt": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time"
                          },
                          "rotatedAt": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time",
                            "description": "When a rotation replaced the key: it works until expiresAt at the latest and cannot be rotated again"
                          }
                        }
                      }
                    },
                    "count": {
                      "type": "number"
                    }
                  }
                },
                "example": {
                  "apiKeys": [
                    {
                      "id": "5e8f1a2b-3c4d-4e5f-8a9b-0c1d2e3f4a5b",
                      "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                      "organizationId": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                      "name": "CRM production",
                      "prefix": "k3x9p2ab",
                      "maskedKey": "wag_live_k3x9p2ab_…",
                      "scopes": [
                        "connections:read",
                        "messages:send"
                      ],
                      "status": "active",
                      "createdBy": "platform",
                      "createdAt": "2026-09-01T12:00:00.000Z",
                      "lastUsedAt": "2026-09-24T12:00:00.000Z",
                      "expiresAt": null,
                      "revokedAt": null,
                      "rotatedAt": null
                    }
                  ],
                  "count": 1
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      },
      "post": {
        "operationId": "createApiKey",
        "summary": "Criar uma chave de API",
        "tags": [
          "API keys"
        ],
        "description": "Cria uma chave para o projeto, enviada como `Authorization: Bearer <chave>` ou `X-Api-Key: <chave>`. A resposta traz a chave uma única vez: guarde-a agora. Uma chave de API só concede escopos que ela mesma tem, e uma chave que expira só cria chaves que expiram até a data dela. Um projeto inativo não recebe chaves novas (409).",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string",
                    "minLength": 1,
                    "maxLength": 100,
                    "description": "What the key is for"
                  },
                  "scopes": {
                    "type": "array",
                    "items": {
                      "type": "string",
                      "enum": [
                        "connections:read",
                        "connections:write",
                        "messages:send",
                        "templates:write",
                        "webhooks:write",
                        "logs:read",
                        "usage:read",
                        "keys:read",
                        "keys:write"
                      ]
                    },
                    "minItems": 1,
                    "uniqueItems": true
                  },
                  "expiresAt": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "format": "date-time",
                    "description": "When the key stops working; null or absent: never"
                  }
                },
                "required": [
                  "name",
                  "scopes"
                ],
                "additionalProperties": false
              },
              "example": {
                "name": "CRM production",
                "scopes": [
                  "connections:read",
                  "messages:send"
                ]
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "keys:write"
            ]
          },
          {
            "apiKeyHeader": [
              "keys:write"
            ]
          }
        ],
        "responses": {
          "201": {
            "description": "The key, with the key itself shown this once.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "tenantId": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "organizationId": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The tenant's organization"
                    },
                    "name": {
                      "type": "string"
                    },
                    "prefix": {
                      "type": "string",
                      "description": "Identifies the key; not secret"
                    },
                    "maskedKey": {
                      "type": "string",
                      "description": "wag_live_<prefix>_…, to recognise the key"
                    },
                    "scopes": {
                      "type": "array",
                      "items": {
                        "type": "string",
                        "enum": [
                          "connections:read",
                          "connections:write",
                          "messages:send",
                          "templates:write",
                          "webhooks:write",
                          "logs:read",
                          "usage:read",
                          "keys:read",
                          "keys:write"
                        ]
                      }
                    },
                    "status": {
                      "type": "string",
                      "enum": [
                        "active",
                        "expired",
                        "revoked"
                      ]
                    },
                    "createdBy": {
                      "type": "string",
                      "description": "\"apiKey:<id>\" of the key that created it, \"user:<id>\" of the dashboard user, or \"platform\""
                    },
                    "createdAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "lastUsedAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time",
                      "description": "Updated at most once a minute"
                    },
                    "expiresAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "revokedAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "rotatedAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time",
                      "description": "When a rotation replaced the key: it works until expiresAt at the latest and cannot be rotated again"
                    },
                    "key": {
                      "type": "string",
                      "description": "The key itself, shown this once: only its SHA-256 is stored, so it cannot be shown again"
                    }
                  },
                  "description": "The key, with the key itself shown this once."
                },
                "example": {
                  "id": "6f9a2b3c-4d5e-4f6a-9b0c-1d2e3f4a5b6c",
                  "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                  "organizationId": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                  "name": "CRM production",
                  "prefix": "q7m4w1zc",
                  "maskedKey": "wag_live_q7m4w1zc_…",
                  "scopes": [
                    "connections:read",
                    "messages:send"
                  ],
                  "status": "active",
                  "createdBy": "platform",
                  "createdAt": "2026-09-24T12:00:00.000Z",
                  "lastUsedAt": null,
                  "expiresAt": null,
                  "revokedAt": null,
                  "rotatedAt": null,
                  "key": "wag_live_q7m4w1zc_AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "Forbidden",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "409": {
            "description": "Conflict",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/tenants/{id}/api-keys/{keyId}": {
      "delete": {
        "operationId": "revokeApiKey",
        "summary": "Revogar uma chave de API",
        "tags": [
          "API keys"
        ],
        "description": "A chave para de funcionar na hora. A linha continua listada (status revoked) para auditoria.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "keyId",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "keys:write"
            ]
          },
          {
            "apiKeyHeader": [
              "keys:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The revoked key.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "tenantId": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "organizationId": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The tenant's organization"
                    },
                    "name": {
                      "type": "string"
                    },
                    "prefix": {
                      "type": "string",
                      "description": "Identifies the key; not secret"
                    },
                    "maskedKey": {
                      "type": "string",
                      "description": "wag_live_<prefix>_…, to recognise the key"
                    },
                    "scopes": {
                      "type": "array",
                      "items": {
                        "type": "string",
                        "enum": [
                          "connections:read",
                          "connections:write",
                          "messages:send",
                          "templates:write",
                          "webhooks:write",
                          "logs:read",
                          "usage:read",
                          "keys:read",
                          "keys:write"
                        ]
                      }
                    },
                    "status": {
                      "type": "string",
                      "enum": [
                        "active",
                        "expired",
                        "revoked"
                      ]
                    },
                    "createdBy": {
                      "type": "string",
                      "description": "\"apiKey:<id>\" of the key that created it, \"user:<id>\" of the dashboard user, or \"platform\""
                    },
                    "createdAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "lastUsedAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time",
                      "description": "Updated at most once a minute"
                    },
                    "expiresAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "revokedAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "rotatedAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time",
                      "description": "When a rotation replaced the key: it works until expiresAt at the latest and cannot be rotated again"
                    }
                  },
                  "description": "The revoked key."
                },
                "example": {
                  "id": "5e8f1a2b-3c4d-4e5f-8a9b-0c1d2e3f4a5b",
                  "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                  "organizationId": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                  "name": "CRM production",
                  "prefix": "k3x9p2ab",
                  "maskedKey": "wag_live_k3x9p2ab_…",
                  "scopes": [
                    "connections:read",
                    "messages:send"
                  ],
                  "status": "revoked",
                  "createdBy": "platform",
                  "createdAt": "2026-09-01T12:00:00.000Z",
                  "lastUsedAt": "2026-09-24T12:00:00.000Z",
                  "expiresAt": null,
                  "revokedAt": "2026-09-24T12:00:00.000Z",
                  "rotatedAt": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "Forbidden",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/tenants/{id}/api-keys/{keyId}/rotate": {
      "post": {
        "operationId": "rotateApiKey",
        "summary": "Rotacionar uma chave de API",
        "tags": [
          "API keys"
        ],
        "description": "Cria uma chave nova com o nome, os escopos e a validade da antiga, mostrada uma única vez. A antiga continua funcionando por overlapSeconds (padrão: 24 horas), para quem chama trocar sem interrupção; 0 a revoga na hora. Uma chave é rotacionada uma vez: rotacioná-la de novo, ou rotacionar uma chave revogada ou expirada, responde 409.",
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "overlapSeconds": {
                    "type": "integer",
                    "minimum": 0,
                    "maximum": 604800
                  }
                },
                "additionalProperties": false
              },
              "example": {
                "overlapSeconds": 3600
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "keyId",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "keys:write"
            ]
          },
          {
            "apiKeyHeader": [
              "keys:write"
            ]
          }
        ],
        "responses": {
          "201": {
            "description": "The new key (shown this once) and the old one, retired after the overlap.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The new key (shown this once) and the old one, retired after the overlap.",
                  "type": "object",
                  "properties": {
                    "apiKey": {
                      "type": "object",
                      "properties": {
                        "id": {
                          "type": "string",
                          "format": "uuid"
                        },
                        "tenantId": {
                          "type": "string",
                          "format": "uuid"
                        },
                        "organizationId": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "description": "The tenant's organization"
                        },
                        "name": {
                          "type": "string"
                        },
                        "prefix": {
                          "type": "string",
                          "description": "Identifies the key; not secret"
                        },
                        "maskedKey": {
                          "type": "string",
                          "description": "wag_live_<prefix>_…, to recognise the key"
                        },
                        "scopes": {
                          "type": "array",
                          "items": {
                            "type": "string",
                            "enum": [
                              "connections:read",
                              "connections:write",
                              "messages:send",
                              "templates:write",
                              "webhooks:write",
                              "logs:read",
                              "usage:read",
                              "keys:read",
                              "keys:write"
                            ]
                          }
                        },
                        "status": {
                          "type": "string",
                          "enum": [
                            "active",
                            "expired",
                            "revoked"
                          ]
                        },
                        "createdBy": {
                          "type": "string",
                          "description": "\"apiKey:<id>\" of the key that created it, \"user:<id>\" of the dashboard user, or \"platform\""
                        },
                        "createdAt": {
                          "type": "string",
                          "format": "date-time"
                        },
                        "lastUsedAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time",
                          "description": "Updated at most once a minute"
                        },
                        "expiresAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time"
                        },
                        "revokedAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time"
                        },
                        "rotatedAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time",
                          "description": "When a rotation replaced the key: it works until expiresAt at the latest and cannot be rotated again"
                        },
                        "key": {
                          "type": "string",
                          "description": "The key itself, shown this once: only its SHA-256 is stored, so it cannot be shown again"
                        }
                      }
                    },
                    "previous": {
                      "type": "object",
                      "properties": {
                        "id": {
                          "type": "string",
                          "format": "uuid"
                        },
                        "tenantId": {
                          "type": "string",
                          "format": "uuid"
                        },
                        "organizationId": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "description": "The tenant's organization"
                        },
                        "name": {
                          "type": "string"
                        },
                        "prefix": {
                          "type": "string",
                          "description": "Identifies the key; not secret"
                        },
                        "maskedKey": {
                          "type": "string",
                          "description": "wag_live_<prefix>_…, to recognise the key"
                        },
                        "scopes": {
                          "type": "array",
                          "items": {
                            "type": "string",
                            "enum": [
                              "connections:read",
                              "connections:write",
                              "messages:send",
                              "templates:write",
                              "webhooks:write",
                              "logs:read",
                              "usage:read",
                              "keys:read",
                              "keys:write"
                            ]
                          }
                        },
                        "status": {
                          "type": "string",
                          "enum": [
                            "active",
                            "expired",
                            "revoked"
                          ]
                        },
                        "createdBy": {
                          "type": "string",
                          "description": "\"apiKey:<id>\" of the key that created it, \"user:<id>\" of the dashboard user, or \"platform\""
                        },
                        "createdAt": {
                          "type": "string",
                          "format": "date-time"
                        },
                        "lastUsedAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time",
                          "description": "Updated at most once a minute"
                        },
                        "expiresAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time"
                        },
                        "revokedAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time"
                        },
                        "rotatedAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time",
                          "description": "When a rotation replaced the key: it works until expiresAt at the latest and cannot be rotated again"
                        }
                      }
                    }
                  }
                },
                "example": {
                  "apiKey": {
                    "id": "6f9a2b3c-4d5e-4f6a-9b0c-1d2e3f4a5b6c",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "organizationId": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                    "name": "CRM production",
                    "prefix": "q7m4w1zc",
                    "maskedKey": "wag_live_q7m4w1zc_…",
                    "scopes": [
                      "connections:read",
                      "messages:send"
                    ],
                    "status": "active",
                    "createdBy": "platform",
                    "createdAt": "2026-09-24T12:00:00.000Z",
                    "lastUsedAt": null,
                    "expiresAt": null,
                    "revokedAt": null,
                    "rotatedAt": null,
                    "key": "wag_live_q7m4w1zc_AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"
                  },
                  "previous": {
                    "id": "5e8f1a2b-3c4d-4e5f-8a9b-0c1d2e3f4a5b",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "organizationId": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                    "name": "CRM production",
                    "prefix": "k3x9p2ab",
                    "maskedKey": "wag_live_k3x9p2ab_…",
                    "scopes": [
                      "connections:read",
                      "messages:send"
                    ],
                    "status": "active",
                    "createdBy": "platform",
                    "createdAt": "2026-09-01T12:00:00.000Z",
                    "lastUsedAt": "2026-09-24T12:00:00.000Z",
                    "expiresAt": "2026-09-24T13:00:00.000Z",
                    "revokedAt": null,
                    "rotatedAt": "2026-09-24T12:00:00.000Z"
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "Forbidden",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "409": {
            "description": "Conflict",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/connections": {
      "get": {
        "operationId": "listConnections",
        "summary": "Listar conexões",
        "tags": [
          "Connections"
        ],
        "description": "As conexões dos projetos ativos de quem chama, com o status atual. As conexões FAILED ficam de fora, a menos que includeFailed=true.",
        "parameters": [
          {
            "schema": {
              "type": "boolean",
              "default": false
            },
            "in": "query",
            "name": "includeFailed",
            "required": false
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The connections, newest first.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The connections, newest first.",
                  "type": "object",
                  "properties": {
                    "connections": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string"
                          },
                          "tenantId": {
                            "type": "string"
                          },
                          "tenantName": {
                            "type": "string"
                          },
                          "lastConnectedAt": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "externalId": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "status": {
                            "type": "string",
                            "description": "Live status when this process holds the socket (connecting, open, close, passkey_required), else the stored one (lowercase)."
                          },
                          "phoneNumber": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "lastHeartbeat": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "createdAt": {
                            "type": "string"
                          }
                        }
                      }
                    },
                    "count": {
                      "type": "number"
                    }
                  }
                },
                "example": {
                  "connections": [
                    {
                      "id": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                      "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                      "tenantName": "acme-crm",
                      "externalId": "shop-42",
                      "status": "open",
                      "phoneNumber": "5511900000001",
                      "lastHeartbeat": "2026-09-24T12:00:00.000Z",
                      "lastConnectedAt": "2026-09-24T08:00:00.000Z",
                      "createdAt": "2026-09-01T12:00:00.000Z"
                    }
                  ],
                  "count": 1
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      },
      "post": {
        "operationId": "createConnection",
        "summary": "Criar uma conexão de WhatsApp",
        "tags": [
          "Connections"
        ],
        "description": "Cria uma conexão de WhatsApp num projeto (ou conecta a que o externalId indica) e devolve o connectionId para parear com o QR code ou com o código de pareamento. Com proxy, ele é verificado antes (400, 422 ou 503 quando recusado, e nada é criado) e gravado antes do primeiro socket: nem o primeiro QR code sai por fora dele. Cada conexão ocupa um dos números que a organização do projeto contratou até ser apagada: além deles, 402 `number_limit_reached` (conectar a que um externalId indica não ocupa outro).",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "tenantId": {
                    "type": "string",
                    "format": "uuid",
                    "description": "Tenant ID"
                  },
                  "externalId": {
                    "type": "string",
                    "description": "Optional tenant-specific identifier (e.g., businessId)"
                  },
                  "proxy": {
                    "type": [
                      "object",
                      "null"
                    ],
                    "required": [
                      "url"
                    ],
                    "additionalProperties": false,
                    "properties": {
                      "url": {
                        "type": "string",
                        "minLength": 1,
                        "maxLength": 2048,
                        "description": "socks5://, socks5h:// (the proxy resolves hostnames in both), http:// or https:// (HTTP CONNECT), with optional user:password@. Write-only."
                      },
                      "country": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "pattern": "^[A-Za-z]{2}$",
                        "description": "The country the proxy must exit from (ISO 3166-1 alpha-2, e.g. BR); omitted or null: any"
                      }
                    },
                    "description": "The connection's own proxy, as PUT /connections/{id}/proxy takes it: its socket, media uploads and downloads leave through it from the first one",
                    "example": {
                      "url": "socks5://user:password@br.proxy.example.com:1080",
                      "country": "BR"
                    }
                  }
                },
                "required": [
                  "tenantId"
                ]
              },
              "example": {
                "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                "externalId": "shop-42"
              }
            }
          }
        },
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The connection: pair it with GET /connections/{id}/qr or POST /connections/{id}/pairing-code.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The connection: pair it with GET /connections/{id}/qr or POST /connections/{id}/pairing-code.",
                  "type": "object",
                  "properties": {
                    "connectionId": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "externalId": {
                      "type": [
                        "string",
                        "null"
                      ]
                    }
                  }
                },
                "example": {
                  "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                  "externalId": "shop-42"
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "422": {
            "description": "The check through the proxy failed: nothing was created.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The check through the proxy failed: nothing was created."
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "description": "This gateway cannot store proxy URLs: no encryption key is configured.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "This gateway cannot store proxy URLs: no encryption key is configured."
                }
              }
            }
          }
        }
      }
    },
    "/connections/{id}/qr": {
      "get": {
        "operationId": "getConnectionQr",
        "summary": "Obter o QR code e o status da conexão",
        "tags": [
          "Connections"
        ],
        "description": "O QR code atual (quando houver) e o status da conexão. O QR code só aparece para quem tem o escopo connections:write: escaneá-lo conecta um número à conexão, como faz POST /connections/{id}/pairing-code. Só com connections:read, qr vem null e o status continua disponível. status passkey_required: o QR foi escaneado, mas o pareamento não terminou porque o WhatsApp pediu uma passkey (chave de acesso) ao celular, o que este gateway ainda não consegue concluir. O socket fica parado (sem novos QR codes) até a conexão ser conectada de novo, inclusive depois de reinícios (o status é gravado); o número pode ser pareado mais tarde, ou outro número pode ser usado.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true,
            "description": "Connection ID"
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The QR code to scan, while the connection is pairing, and the status.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The QR code to scan, while the connection is pairing, and the status.",
                  "type": "object",
                  "properties": {
                    "qr": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "QR code string for scanning; null when there is none, or the caller lacks connections:write"
                    },
                    "status": {
                      "type": "string",
                      "enum": [
                        "connecting",
                        "open",
                        "close",
                        "passkey_required"
                      ]
                    }
                  }
                },
                "example": {
                  "qr": "2@k8Jd0Qf3mX1pT7vZ9sLr4eYw6nHc2bGa,5oVt8yRk3uEi1wQz7xNm4cPl0dFg6hJs=,Zx9Cv8Bn7Ma6Sd5Fg4Hj3Kl2",
                  "status": "connecting"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/pairing-code": {
      "post": {
        "operationId": "requestPairingCode",
        "summary": "Obter um código de pareamento para conectar um número sem o QR code",
        "tags": [
          "Connections"
        ],
        "description": "Pede ao WhatsApp um código de 8 caracteres que conecta phone à conexão quando é digitado nesse celular (WhatsApp › Aparelhos conectados › Conectar um aparelho › Conectar com número de telefone), em vez de escanear o QR code. Só enquanto a conexão está pareando com o QR code na tela (GET /connections/{id}/qr mostra um): crie a conexão, ou conecte-a de novo, antes. O celular recebe um aviso. O código vale até expiresAt, quando terminam os QR codes dessa tentativa (no máximo cerca de 2,5 minutos depois de eles aparecerem) e a conexão mostra QR codes novos: peça outro código então. Quando eles terminam cedo demais para o código ser digitado, 409 not_pairing com Retry-After diz quando os próximos aparecem. Cada código gera um aviso no celular, então uma conexão pode pedir um a cada 30 segundos e um número recebe no máximo 5 por hora, qualquer que seja a conexão que pede (429 pairing_code_too_soon com Retry-After). Depois, o pareamento termina como o do QR code (status open, connection.status open). **Um código de pareamento não evita a passkey**: quando o WhatsApp pede uma passkey ao celular depois do código digitado, o pareamento trava exatamente como depois da leitura do QR code e a conexão para como passkey_required.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "phone": {
                    "type": "string",
                    "minLength": 8,
                    "maxLength": 32,
                    "description": "The number to link, in international format: country code first (digits; +, spaces, dashes and parentheses are ignored)"
                  }
                },
                "required": [
                  "phone"
                ]
              },
              "example": {
                "phone": "5511900000001"
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The code to type on the phone, the number it links (E.164) and until when it can be typed.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The code to type on the phone, the number it links (E.164) and until when it can be typed.",
                  "type": "object",
                  "properties": {
                    "code": {
                      "type": "string",
                      "description": "The pairing code, 8 characters; WhatsApp shows it as two groups of 4 (K7QX-2M9P)"
                    },
                    "phone": {
                      "type": "string",
                      "description": "The number it links, E.164"
                    },
                    "expiresAt": {
                      "type": "number",
                      "description": "Unix ms the code stops working: the QR codes of this pairing end, and the connection shows new ones"
                    }
                  }
                },
                "example": {
                  "code": "K7QX2M9P",
                  "phone": "+5511900000001",
                  "expiresAt": 1790251365000
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "description": "No pairing a code could join: `already_paired` (the connection is linked to a number, or a link is completing: log it out to link another) or `not_pairing` (it is not pairing with a QR code up: connect it again, or retry in a few seconds while it starts; with Retry-After when its QR codes end too soon for a code to be typed).",
            "content": {
              "application/json": {
                "schema": {
                  "description": "No pairing a code could join: `already_paired` (the connection is linked to a number, or a link is completing: log it out to link another) or `not_pairing` (it is not pairing with a QR code up: connect it again, or retry in a few seconds while it starts; with Retry-After when its QR codes end too soon for a code to be typed).",
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "required": [
                    "error"
                  ]
                },
                "example": {
                  "error": "not_pairing",
                  "message": "The connection is not pairing with its QR code up (status: close): connect it again, then ask for a code"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "error": "Failed to request a pairing code"
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/send": {
      "post": {
        "operationId": "sendMessage",
        "summary": "Enfileirar uma mensagem para envio",
        "tags": [
          "Messages"
        ],
        "description": "Enfileira uma mensagem (texto, mídia, localização ou template) para envio com ritmo controlado: a resposta é o job na fila, e os webhooks message.outgoing / message.delivery informam o que aconteceu com ele. Envie um clientRef para tornar a requisição idempotente e correlacionar esses eventos. 429 quando a cota do plano da organização do projeto acabou (as mensagens enviadas e enfileiradas de todos os projetos dela contam juntas; X-Usage-Percent), e 429 new_recipient_cap_reached (com Retry-After) quando o destinatário não trocou mensagem com o número nos últimos 28 dias desde a conexão atual (parear de novo, mesmo o mesmo número, torna todos os contatos novos) e o número já alcançou o limite de destinatários novos das últimas 24 horas (menor enquanto ele está conectado há menos de 14 dias; GET /connections/{id}/queue mostra o limite e o uso): um contato frio abordado demais faz o WhatsApp restringir o número. 400 invalid_recipient quando to não é um número de telefone nem o JID de uma pessoa, de um grupo, de uma lista de transmissão ou de um canal.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "to": {
                    "type": "string",
                    "description": "Recipient: a phone number, country code first (e.g., 5511999999999; its digits are read), or a JID (a person @s.whatsapp.net or @lid, a group @g.us)"
                  },
                  "message": {
                    "type": "string",
                    "description": "Text message content"
                  },
                  "typingDelay": {
                    "type": "number",
                    "description": "Typing indicator duration in ms (default: 1500)"
                  },
                  "media": {
                    "type": "object",
                    "properties": {
                      "type": {
                        "type": "string",
                        "enum": [
                          "image",
                          "video",
                          "audio",
                          "document",
                          "sticker"
                        ]
                      },
                      "url": {
                        "type": "string",
                        "format": "uri",
                        "pattern": "^https://",
                        "description": "Public https URL; private and internal addresses are refused"
                      },
                      "caption": {
                        "type": "string"
                      },
                      "fileName": {
                        "type": "string"
                      },
                      "mimetype": {
                        "type": "string"
                      },
                      "ptt": {
                        "type": "boolean",
                        "description": "Push-to-talk (voice note) for audio"
                      },
                      "gifPlayback": {
                        "type": "boolean",
                        "description": "Play video as GIF"
                      }
                    },
                    "required": [
                      "type",
                      "url"
                    ]
                  },
                  "location": {
                    "type": "object",
                    "properties": {
                      "latitude": {
                        "type": "number"
                      },
                      "longitude": {
                        "type": "number"
                      },
                      "name": {
                        "type": "string"
                      },
                      "address": {
                        "type": "string"
                      }
                    },
                    "required": [
                      "latitude",
                      "longitude"
                    ]
                  },
                  "template": {
                    "type": "string",
                    "description": "Template name to use"
                  },
                  "variables": {
                    "type": "object",
                    "additionalProperties": {
                      "type": "string"
                    },
                    "description": "Template variable values"
                  },
                  "clientRef": {
                    "type": "string",
                    "maxLength": 200,
                    "description": "Optional consumer id for this send. Echoed as clientRef on the message.outgoing (origin API) and message.delivery events of the message, so the consumer can correlate them without knowing the WhatsApp message id in advance. Also the idempotency key: a repeat with the same clientRef on the same connection is answered 200 with the original job and queues nothing."
                  }
                },
                "required": [
                  "to"
                ]
              },
              "examples": {
                "example1": {
                  "value": {
                    "to": "5511988887777",
                    "message": "Your appointment is confirmed for tomorrow at 10:00",
                    "clientRef": "crm-msg-1"
                  }
                },
                "example2": {
                  "value": {
                    "to": "5511988887777",
                    "media": {
                      "type": "image",
                      "url": "https://cdn.example.com/promo-october.jpg",
                      "caption": "October promo"
                    },
                    "clientRef": "crm-msg-2"
                  }
                },
                "example3": {
                  "value": {
                    "to": "5511988887777",
                    "template": "appointment_confirmation",
                    "variables": {
                      "name": "Maria",
                      "time": "10:00"
                    },
                    "clientRef": "crm-msg-3"
                  }
                }
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "messages:send"
            ]
          },
          {
            "apiKeyHeader": [
              "messages:send"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "A previous request with the same clientRef already queued this message; its job is returned and nothing is queued again.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "A previous request with the same clientRef already queued this message; its job is returned and nothing is queued again.",
                  "type": "object",
                  "properties": {
                    "jobId": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "scheduledAt": {
                      "type": [
                        "null",
                        "number"
                      ]
                    },
                    "position": {
                      "type": [
                        "null",
                        "number"
                      ]
                    },
                    "duplicate": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "jobId": "c2a4e6f8-1b3d-4f5a-8c7e-9d0b1a2c3e4f",
                  "scheduledAt": 1790251205000,
                  "position": 1,
                  "duplicate": true
                }
              }
            }
          },
          "202": {
            "description": "Queued.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Queued.",
                  "type": "object",
                  "properties": {
                    "jobId": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "scheduledAt": {
                      "type": "number",
                      "description": "Unix ms when the send is due."
                    },
                    "position": {
                      "type": "number",
                      "description": "Place in the connection's queue."
                    }
                  }
                },
                "example": {
                  "jobId": "c2a4e6f8-1b3d-4f5a-8c7e-9d0b1a2c3e4f",
                  "scheduledAt": 1790251205000,
                  "position": 1
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "required": [
                    "error"
                  ]
                },
                "example": {
                  "error": "invalid_recipient",
                  "message": "to must be a phone number (country code first) or the JID of a person (@s.whatsapp.net, @lid), a group (@g.us), a broadcast list or a newsletter"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/queue": {
      "get": {
        "operationId": "getQueue",
        "summary": "Consultar a fila de uma conexão",
        "tags": [
          "Messages"
        ],
        "description": "Estatísticas da fila e uso dos limites de envio, com o limite de destinatários novos por 24 horas e o aquecimento de um número conectado há menos de 14 dias.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The queue and the pacing limits.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The queue and the pacing limits.",
                  "type": "object",
                  "properties": {
                    "pending": {
                      "type": "number"
                    },
                    "scheduled": {
                      "type": "number"
                    },
                    "limits": {
                      "type": "object",
                      "properties": {
                        "perMinute": {
                          "type": "number"
                        },
                        "perHour": {
                          "type": "number"
                        },
                        "perDay": {
                          "type": "number"
                        },
                        "newRecipientsPerDay": {
                          "type": [
                            "number",
                            "null"
                          ],
                          "description": "Unique recipients who exchanged no message with the number in the last 28 days since its current link it may be sent to per rolling 24 hours; null: no cap"
                        }
                      }
                    },
                    "usage": {
                      "type": "object",
                      "properties": {
                        "minute": {
                          "type": "number"
                        },
                        "hour": {
                          "type": "number"
                        },
                        "day": {
                          "type": "number"
                        },
                        "newRecipients": {
                          "type": "number",
                          "description": "New recipients counted in the last 24 hours"
                        }
                      }
                    },
                    "warmup": {
                      "type": "object",
                      "description": "The warm-up of a freshly linked number: for 14 days after its link its limits are lower, and loosen step by step.",
                      "properties": {
                        "createdAt": {
                          "type": "number",
                          "description": "Unix ms the warm-up counts from: when the number was linked"
                        },
                        "messagesSent": {
                          "type": "number"
                        },
                        "isInWarmup": {
                          "type": "boolean"
                        },
                        "endsAt": {
                          "type": "number",
                          "description": "Unix ms the warm-up ends"
                        }
                      }
                    }
                  }
                },
                "example": {
                  "pending": 1,
                  "scheduled": 2,
                  "limits": {
                    "perMinute": 3,
                    "perHour": 60,
                    "perDay": 200,
                    "newRecipientsPerDay": 100
                  },
                  "usage": {
                    "minute": 1,
                    "hour": 12,
                    "day": 40,
                    "newRecipients": 7
                  },
                  "warmup": {
                    "createdAt": 1789646400000,
                    "messagesSent": 40,
                    "isInWarmup": false,
                    "endsAt": 1790856000000
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/queue/{jobId}": {
      "delete": {
        "operationId": "cancelQueuedMessage",
        "summary": "Cancelar uma mensagem na fila",
        "tags": [
          "Messages"
        ],
        "description": "Remove uma mensagem da fila antes do envio.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "jobId",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "messages:send"
            ]
          },
          {
            "apiKeyHeader": [
              "messages:send"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Removed from the queue.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Removed from the queue.",
                  "type": "object",
                  "properties": {
                    "cancelled": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "cancelled": true
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/connections/{id}/contacts/check": {
      "post": {
        "operationId": "checkContacts",
        "summary": "Verificar se números estão no WhatsApp",
        "tags": [
          "Contacts"
        ],
        "description": "Valida até 100 números de telefone e responde se estão registrados no WhatsApp.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "phones": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    },
                    "maxItems": 100,
                    "description": "Array of phone numbers to check"
                  }
                },
                "required": [
                  "phones"
                ]
              },
              "example": {
                "phones": [
                  "5511988887777",
                  "5511955550000"
                ]
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "messages:send"
            ]
          },
          {
            "apiKeyHeader": [
              "messages:send"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "One result per phone, in order.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "One result per phone, in order.",
                  "type": "object",
                  "properties": {
                    "results": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "phone": {
                            "type": "string"
                          },
                          "exists": {
                            "type": "boolean"
                          },
                          "jid": {
                            "type": "string"
                          }
                        }
                      }
                    }
                  }
                },
                "example": {
                  "results": [
                    {
                      "phone": "5511988887777",
                      "exists": true,
                      "jid": "5511988887777@s.whatsapp.net"
                    },
                    {
                      "phone": "5511955550000",
                      "exists": false
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "error": "Failed to check contacts"
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/profile/{phone}": {
      "get": {
        "operationId": "getContactProfile",
        "summary": "Consultar o perfil de um contato",
        "tags": [
          "Contacts"
        ],
        "description": "O recado do perfil e a URL da foto de um contato.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string"
            },
            "in": "path",
            "name": "phone",
            "required": true,
            "description": "Phone number"
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "messages:send"
            ]
          },
          {
            "apiKeyHeader": [
              "messages:send"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "What WhatsApp shows of the contact; absent fields are hidden by its privacy settings.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "What WhatsApp shows of the contact; absent fields are hidden by its privacy settings.",
                  "type": "object",
                  "properties": {
                    "phone": {
                      "type": "string"
                    },
                    "name": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "status": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "pictureUrl": {
                      "type": [
                        "string",
                        "null"
                      ]
                    }
                  }
                },
                "example": {
                  "phone": "5511988887777",
                  "status": "Available",
                  "pictureUrl": "https://pps.whatsapp.net/v/t61.24694-24/profile.jpg"
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "error": "Failed to get profile"
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/react": {
      "post": {
        "operationId": "sendReaction",
        "summary": "Reagir a uma mensagem",
        "tags": [
          "Messages"
        ],
        "description": "Envia uma reação com emoji a uma mensagem. Use uma string vazia para remover a reação.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "messageId": {
                    "type": "string",
                    "description": "ID of the message to react to"
                  },
                  "to": {
                    "type": "string",
                    "description": "Recipient phone number"
                  },
                  "emoji": {
                    "type": "string",
                    "description": "Emoji to react with (empty to remove)"
                  }
                },
                "required": [
                  "messageId",
                  "to"
                ]
              },
              "example": {
                "messageId": "3EB0C767D26A1D8A3F52",
                "to": "5511988887777",
                "emoji": "👍"
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "messages:send"
            ]
          },
          {
            "apiKeyHeader": [
              "messages:send"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Sent.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Sent.",
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "success": true
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "error": "Failed to send reaction"
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/groups": {
      "get": {
        "operationId": "listGroups",
        "summary": "Listar grupos",
        "tags": [
          "Connections"
        ],
        "description": "Os grupos de que o número pareado participa, consultados no WhatsApp. A conexão precisa estar aberta (400 caso contrário), e o provedor dela precisa suportar grupos (501 caso contrário).",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The groups.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The groups.",
                  "type": "object",
                  "properties": {
                    "groups": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "jid": {
                            "type": "string",
                            "description": "Group JID (…@g.us)"
                          },
                          "subject": {
                            "type": "string"
                          },
                          "size": {
                            "type": "number",
                            "description": "Participants"
                          }
                        }
                      }
                    }
                  }
                },
                "example": {
                  "groups": [
                    {
                      "jid": "120363040000000001@g.us",
                      "subject": "Barber team",
                      "size": 3
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/disconnect": {
      "post": {
        "operationId": "disconnectConnection",
        "summary": "Desconectar uma conexão do WhatsApp",
        "tags": [
          "Connections"
        ],
        "description": "Fecha a conexão com o WhatsApp. A sessão é preservada para reconectar.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Done.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Done.",
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "ok": true
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/logout": {
      "post": {
        "operationId": "logoutConnection",
        "summary": "Sair do WhatsApp (logout)",
        "tags": [
          "Connections"
        ],
        "description": "Sai do WhatsApp e apaga a sessão. Um novo QR code será necessário para conectar de novo. Use para conectar outro número.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Done.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Done.",
                  "type": "object",
                  "properties": {
                    "ok": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "ok": true
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/messages/{messageId}/edit": {
      "post": {
        "operationId": "editMessage",
        "summary": "Editar uma mensagem enviada",
        "tags": [
          "Messages"
        ],
        "description": "Substitui o texto de uma mensagem que este número enviou pela API (o messageId da resposta do /send ou do evento message.outgoing) em até 15 minutos após o envio, como o WhatsApp permite; os destinatários a veem marcada como editada. 404 para uma mensagem que a API não enviou por esta conexão (ou enviou há mais de 72 horas), 409 edit_window_closed depois de 15 minutos.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "additionalProperties": false,
                "properties": {
                  "to": {
                    "type": "string",
                    "minLength": 1,
                    "description": "The chat: a phone number (digits, country code first; the JID WhatsApp registered for it is used, as a send does) or a JID used as is (a group's, or the `jid` of a webhook event, which may be a LID)"
                  },
                  "text": {
                    "type": "string",
                    "minLength": 1,
                    "maxLength": 4096,
                    "description": "The new text"
                  }
                },
                "required": [
                  "to",
                  "text"
                ]
              },
              "example": {
                "to": "5511988887777",
                "text": "Seu horário foi confirmado para as 15h."
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "minLength": 1
            },
            "in": "path",
            "name": "messageId",
            "required": true,
            "description": "The WhatsApp id of a message this number sent through the API"
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "messages:send"
            ]
          },
          {
            "apiKeyHeader": [
              "messages:send"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Done.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Done.",
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "success": true
                }
              }
            }
          },
          "400": {
            "description": "The body is invalid, the connection is not open, or `to` is not on WhatsApp (`not_on_whatsapp`).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The body is invalid, the connection is not open, or `to` is not on WhatsApp (`not_on_whatsapp`)."
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "409": {
            "description": "Conflict",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "error": "Failed to edit the message"
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/messages/{messageId}": {
      "delete": {
        "operationId": "deleteMessage",
        "summary": "Apagar uma mensagem enviada para todos",
        "tags": [
          "Messages"
        ],
        "description": "Apaga para todos uma mensagem que este número enviou pela API (o seu messageId): os destinatários veem \"mensagem apagada\". O WhatsApp respeita o pedido por cerca de dois dias após o envio. 404 para uma mensagem que a API não enviou por esta conexão (ou enviou há mais de 72 horas).",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "additionalProperties": false,
                "properties": {
                  "to": {
                    "type": "string",
                    "minLength": 1,
                    "description": "The chat: a phone number (digits, country code first; the JID WhatsApp registered for it is used, as a send does) or a JID used as is (a group's, or the `jid` of a webhook event, which may be a LID)"
                  }
                },
                "required": [
                  "to"
                ]
              },
              "example": {
                "to": "5511988887777"
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string",
              "minLength": 1
            },
            "in": "path",
            "name": "messageId",
            "required": true,
            "description": "The WhatsApp id of a message this number sent through the API"
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "messages:send"
            ]
          },
          {
            "apiKeyHeader": [
              "messages:send"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Done.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Done.",
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "success": true
                }
              }
            }
          },
          "400": {
            "description": "The body is invalid, the connection is not open, or `to` is not on WhatsApp (`not_on_whatsapp`).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The body is invalid, the connection is not open, or `to` is not on WhatsApp (`not_on_whatsapp`)."
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "error": "Failed to delete the message"
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/read": {
      "post": {
        "operationId": "markMessagesRead",
        "summary": "Marcar mensagens recebidas como lidas",
        "tags": [
          "Messages"
        ],
        "description": "Envia confirmações de leitura (tiques azuis) de mensagens recebidas em uma conversa: os messageId dos eventos message.incoming e, como to, o jid desses eventos. Em um grupo, to é o grupo e participant o JID de quem enviou as mensagens. Até 100 mensagens por chamada.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "additionalProperties": false,
                "properties": {
                  "to": {
                    "type": "string",
                    "minLength": 1,
                    "description": "The chat: a phone number (digits, country code first; the JID WhatsApp registered for it is used, as a send does) or a JID used as is (a group's, or the `jid` of a webhook event, which may be a LID)"
                  },
                  "messageIds": {
                    "type": "array",
                    "minItems": 1,
                    "maxItems": 100,
                    "items": {
                      "type": "string",
                      "minLength": 1
                    }
                  },
                  "participant": {
                    "type": "string",
                    "minLength": 1,
                    "description": "In a group: the JID of whoever sent the messages"
                  }
                },
                "required": [
                  "to",
                  "messageIds"
                ]
              },
              "example": {
                "to": "5511988887777@s.whatsapp.net",
                "messageIds": [
                  "3EB0C767D26A1D8A3F52"
                ]
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "messages:send"
            ]
          },
          {
            "apiKeyHeader": [
              "messages:send"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Done.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Done.",
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "success": true
                }
              }
            }
          },
          "400": {
            "description": "The body is invalid, the connection is not open, or `to` is not on WhatsApp (`not_on_whatsapp`).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The body is invalid, the connection is not open, or `to` is not on WhatsApp (`not_on_whatsapp`)."
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "error": "Failed to mark the messages read"
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/presence": {
      "post": {
        "operationId": "sendPresence",
        "summary": "Mostrar uma presença em uma conversa",
        "tags": [
          "Messages"
        ],
        "description": "Mostra ao contato \"digitando…\" (composing) ou \"gravando áudio…\" (recording) até paused ou até uma mensagem ser enviada; available mostra o número online para todos (to não é usado). Os envios já mostram \"digitando…\" antes de sair: isto serve para uma pausa que quem chama controla, como um atendente escrevendo uma resposta.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "additionalProperties": false,
                "properties": {
                  "to": {
                    "type": "string",
                    "minLength": 1,
                    "description": "The chat: a phone number (digits, country code first; the JID WhatsApp registered for it is used, as a send does) or a JID used as is (a group's, or the `jid` of a webhook event, which may be a LID)"
                  },
                  "state": {
                    "type": "string",
                    "enum": [
                      "composing",
                      "recording",
                      "paused",
                      "available"
                    ]
                  }
                },
                "required": [
                  "to",
                  "state"
                ]
              },
              "example": {
                "to": "5511988887777",
                "state": "composing"
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "messages:send"
            ]
          },
          {
            "apiKeyHeader": [
              "messages:send"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Done.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Done.",
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "success": true
                }
              }
            }
          },
          "400": {
            "description": "The body is invalid, the connection is not open, or `to` is not on WhatsApp (`not_on_whatsapp`).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The body is invalid, the connection is not open, or `to` is not on WhatsApp (`not_on_whatsapp`)."
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "error": "Failed to send the presence"
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/connections/{id}/proxy": {
      "get": {
        "operationId": "getConnectionProxy",
        "summary": "Obter o proxy de uma conexão",
        "tags": [
          "Connections"
        ],
        "description": "O proxy pelo qual saem o socket da conexão e os uploads e downloads de mídia, sem as credenciais, e onde a última verificação o viu sair.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The connection's proxy, or null.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The connection's proxy, or null.",
                  "type": "object",
                  "properties": {
                    "proxy": {
                      "type": [
                        "object",
                        "null"
                      ],
                      "description": "The connection's proxy; null when it connects directly. Its URL and credentials are write-only: never answered.",
                      "properties": {
                        "scheme": {
                          "type": "string",
                          "enum": [
                            "socks5",
                            "socks5h",
                            "http",
                            "https"
                          ]
                        },
                        "host": {
                          "type": "string"
                        },
                        "port": {
                          "type": "integer"
                        },
                        "hasCredentials": {
                          "type": "boolean",
                          "description": "Whether the URL carries a username and password"
                        },
                        "country": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "description": "The country the proxy must exit from (ISO 3166-1 alpha-2), checked before pairing; null: any"
                        },
                        "exit": {
                          "type": [
                            "object",
                            "null"
                          ],
                          "description": "Where the last exit check through the proxy saw it exit: the IP WhatsApp sees the number at",
                          "properties": {
                            "ip": {
                              "type": "string"
                            },
                            "country": {
                              "type": [
                                "string",
                                "null"
                              ],
                              "description": "ISO 3166-1 alpha-2; null when the IP echo endpoint does not tell"
                            },
                            "checkedAt": {
                              "type": "string",
                              "format": "date-time"
                            }
                          }
                        }
                      }
                    }
                  }
                },
                "examples": {
                  "example1": {
                    "value": {
                      "proxy": {
                        "scheme": "socks5",
                        "host": "br.proxy.example.com",
                        "port": 1080,
                        "hasCredentials": true,
                        "country": "BR",
                        "exit": {
                          "ip": "203.0.113.7",
                          "country": "BR",
                          "checkedAt": "2026-09-24T12:00:00.000Z"
                        }
                      }
                    }
                  },
                  "example2": {
                    "value": {
                      "proxy": null
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "The stored proxy cannot be opened; the gateway operator has to fix it.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The stored proxy cannot be opened; the gateway operator has to fix it."
                }
              }
            }
          }
        }
      },
      "put": {
        "operationId": "setConnectionProxy",
        "summary": "Definir o proxy de uma conexão",
        "tags": [
          "Connections"
        ],
        "description": "Traga o seu próprio proxy: a partir de agora, o socket de WhatsApp da conexão e os uploads e downloads de mídia (os dela e as buscas que o gateway faz nas URLs das suas mídias) saem por ele, nunca por fora dele. Antes de ser salvo, o host do proxy precisa ser público e uma requisição por ele precisa dizer por onde ele sai (e, com country, sair nesse país); a mesma verificação roda de novo antes de o número parear, e nenhum QR code é mostrado a partir de uma saída não verificada. Numa conexão ativa, um proxy novo é uma reconexão planejada por ele; o mesmo proxy de novo (só com um country novo) não reconecta nada. A URL é gravada criptografada e nunca é devolvida. Para uma conexão nova usar um proxy desde o primeiro socket, informe-o ao criar a conexão. Responde 503 quando o gateway não consegue guardar segredos (nenhuma chave de criptografia configurada), 422 quando a verificação pelo proxy falha (dizendo apenas como: inalcançável, credenciais recusadas, sem endereço de saída, outro país) e 429 quando as verificações de proxy da organização para esta hora se esgotaram.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "url"
                ],
                "additionalProperties": false,
                "properties": {
                  "url": {
                    "type": "string",
                    "minLength": 1,
                    "maxLength": 2048,
                    "description": "socks5://, socks5h:// (the proxy resolves hostnames in both), http:// or https:// (HTTP CONNECT), with optional user:password@. Write-only."
                  },
                  "country": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "pattern": "^[A-Za-z]{2}$",
                    "description": "The country the proxy must exit from (ISO 3166-1 alpha-2, e.g. BR); omitted or null: any"
                  }
                }
              },
              "example": {
                "url": "socks5://user:password@br.proxy.example.com:1080",
                "country": "BR"
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The proxy, as saved, and whether the live socket reconnected through it.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The proxy, as saved, and whether the live socket reconnected through it.",
                  "type": "object",
                  "properties": {
                    "proxy": {
                      "type": [
                        "object",
                        "null"
                      ],
                      "description": "The connection's proxy; null when it connects directly. Its URL and credentials are write-only: never answered.",
                      "properties": {
                        "scheme": {
                          "type": "string",
                          "enum": [
                            "socks5",
                            "socks5h",
                            "http",
                            "https"
                          ]
                        },
                        "host": {
                          "type": "string"
                        },
                        "port": {
                          "type": "integer"
                        },
                        "hasCredentials": {
                          "type": "boolean",
                          "description": "Whether the URL carries a username and password"
                        },
                        "country": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "description": "The country the proxy must exit from (ISO 3166-1 alpha-2), checked before pairing; null: any"
                        },
                        "exit": {
                          "type": [
                            "object",
                            "null"
                          ],
                          "description": "Where the last exit check through the proxy saw it exit: the IP WhatsApp sees the number at",
                          "properties": {
                            "ip": {
                              "type": "string"
                            },
                            "country": {
                              "type": [
                                "string",
                                "null"
                              ],
                              "description": "ISO 3166-1 alpha-2; null when the IP echo endpoint does not tell"
                            },
                            "checkedAt": {
                              "type": "string",
                              "format": "date-time"
                            }
                          }
                        }
                      }
                    },
                    "reconnecting": {
                      "type": "boolean",
                      "description": "Whether a new socket through the new proxy is on its way (a planned reconnect of a socket that is up, or on its way up). false: the connection is stopped and uses it from its next connect, the proxy is the one it had (only the country changed), or the check before pairing refused it and the connection was stopped (its lastError says why)."
                    }
                  }
                },
                "example": {
                  "proxy": {
                    "scheme": "socks5",
                    "host": "br.proxy.example.com",
                    "port": 1080,
                    "hasCredentials": true,
                    "country": "BR",
                    "exit": {
                      "ip": "203.0.113.7",
                      "country": "BR",
                      "checkedAt": "2026-09-24T12:00:00.000Z"
                    }
                  },
                  "reconnecting": true
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "422": {
            "description": "The check through the proxy failed: it did not answer, refused the credentials, or exits outside the country asked for.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The check through the proxy failed: it did not answer, refused the credentials, or exits outside the country asked for."
                },
                "example": {
                  "error": "Proxy check failed for socks5://br.proxy.example.com:1080: the proxy could not be reached, or did not reach the IP echo endpoint"
                }
              }
            }
          },
          "429": {
            "description": "The organization's proxy checks for this hour are used up, or the rate limit per client IP: Retry-After says in how many seconds to try again.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The organization's proxy checks for this hour are used up, or the rate limit per client IP: Retry-After says in how many seconds to try again."
                }
              }
            }
          },
          "501": {
            "description": "The connection's provider cannot do this: `unsupported_by_provider`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "The connection's provider cannot do this: `unsupported_by_provider`."
                },
                "example": {
                  "error": "unsupported_by_provider"
                }
              }
            }
          },
          "503": {
            "description": "This gateway cannot store proxy URLs: no encryption key is configured.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "This gateway cannot store proxy URLs: no encryption key is configured."
                }
              }
            }
          }
        }
      },
      "delete": {
        "operationId": "deleteConnectionProxy",
        "summary": "Remover o proxy de uma conexão",
        "tags": [
          "Connections"
        ],
        "description": "A conexão passa a se conectar diretamente: uma conexão ativa se reconecta sem o proxy (uma reconexão planejada).",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:write"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Removed (or there was none).",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Removed (or there was none).",
                  "type": "object",
                  "properties": {
                    "proxy": {
                      "type": "null"
                    },
                    "reconnecting": {
                      "type": "boolean",
                      "description": "Whether a new socket through the new proxy is on its way (a planned reconnect of a socket that is up, or on its way up). false: the connection is stopped and uses it from its next connect, the proxy is the one it had (only the country changed), or the check before pairing refused it and the connection was stopped (its lastError says why)."
                    }
                  }
                },
                "example": {
                  "proxy": null,
                  "reconnecting": true
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/connections/{id}/dedicated-ip": {
      "get": {
        "operationId": "getConnectionDedicatedIp",
        "summary": "Obter o IP dedicado de uma conexão",
        "tags": [
          "Connections"
        ],
        "description": "Se o número tem o adicional de IP dedicado: um IP fixo de provedor residencial brasileiro só dele, em vez de um IP que ele divide com, no máximo, alguns outros números do mesmo tenant. É comprado por número pelos donos e administradores da organização no painel (uma assinatura mensal); depois do pagamento, o número passa para o IP dedicado em poucos minutos (uma reconexão planejada), ou assim que um IP é comprado para ele.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The connection's live add-on, else its latest, or null.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The connection's live add-on, else its latest, or null.",
                  "type": "object",
                  "properties": {
                    "dedicatedIp": {
                      "type": [
                        "object",
                        "null"
                      ],
                      "description": "The connection's dedicated-IP add-on: its live one (provisioning or active), else its latest; null when it never had one.",
                      "properties": {
                        "id": {
                          "type": "string",
                          "format": "uuid"
                        },
                        "connectionId": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "uuid"
                        },
                        "status": {
                          "type": "string",
                          "enum": [
                            "awaiting_payment",
                            "provisioning",
                            "active",
                            "canceled"
                          ],
                          "description": "awaiting_payment: its checkout is not paid yet; provisioning: paid, the number is not on its dedicated IP yet; active: the number goes through an IP of its own; canceled: its subscription ended (the number is back on a shared IP)"
                        },
                        "waived": {
                          "type": "boolean",
                          "description": "Granted by the gateway operator, without a subscription"
                        },
                        "lastError": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "description": "Why it is not active: waiting_for_proxy (its dedicated IP is being bought), own_proxy (the connection goes through its own proxy, which wins), connection_deleted, duplicate (a second add-on paid for a connection that has one), unplaced (ended, and no shared IP has room for the number yet)"
                        },
                        "requestedAt": {
                          "type": "string",
                          "format": "date-time"
                        },
                        "paidAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time"
                        },
                        "activatedAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time"
                        },
                        "canceledAt": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "format": "date-time"
                        }
                      }
                    }
                  }
                },
                "examples": {
                  "example1": {
                    "value": {
                      "dedicatedIp": {
                        "id": "f5a6b7c8-d9e0-4f1a-8b2c-3d4e5f6a7b8c",
                        "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                        "status": "active",
                        "waived": false,
                        "lastError": null,
                        "requestedAt": "2026-09-24T12:00:00.000Z",
                        "paidAt": "2026-09-24T12:00:00.000Z",
                        "activatedAt": "2026-09-24T12:00:00.000Z",
                        "canceledAt": null
                      }
                    }
                  },
                  "example2": {
                    "value": {
                      "dedicatedIp": null
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/media/{connectionId}/{fileName}": {
      "get": {
        "operationId": "getMedia",
        "summary": "Baixar um arquivo de mídia",
        "tags": [
          "Media"
        ],
        "description": "Baixa um arquivo de mídia recebido, sem credencial, pela URL assinada que o webhook message.incoming traz em data.media.url (válida até data.media.expiresAt). Use a URL exatamente como recebida: sem assinatura, expirada ou alterada, ela responde 404, como um arquivo que não existe.",
        "parameters": [
          {
            "schema": {
              "type": "string"
            },
            "in": "query",
            "name": "exp",
            "required": false,
            "description": "Unix seconds after which the URL answers 404."
          },
          {
            "schema": {
              "type": "string"
            },
            "in": "query",
            "name": "sig",
            "required": false,
            "description": "base64url HMAC-SHA256 over connectionId/fileName/exp."
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "connectionId",
            "required": true
          },
          {
            "schema": {
              "type": "string"
            },
            "in": "path",
            "name": "fileName",
            "required": true
          }
        ],
        "security": [],
        "responses": {
          "200": {
            "description": "The file, with the Content-Type of its extension (image/jpeg, video/mp4, audio/ogg, application/pdf, …), cacheable until the URL expires.",
            "content": {
              "*/*": {
                "schema": {
                  "type": "string",
                  "format": "binary"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "404": {
            "description": "Unsigned, expired, altered or missing: all answer alike.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ],
                  "description": "Unsigned, expired, altered or missing: all answer alike."
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/connections/{id}/templates": {
      "post": {
        "operationId": "createTemplate",
        "summary": "Criar um template de mensagem",
        "tags": [
          "Templates"
        ],
        "description": "Cria um template de mensagem reutilizável com variáveis ({{nome}}).",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string",
                    "description": "Template name (unique per connection)"
                  },
                  "body": {
                    "type": "string",
                    "description": "Template body with {{variables}}"
                  },
                  "media": {
                    "type": "object",
                    "properties": {
                      "type": {
                        "type": "string",
                        "enum": [
                          "image",
                          "video",
                          "audio",
                          "document",
                          "sticker"
                        ]
                      },
                      "url": {
                        "type": "string",
                        "format": "uri",
                        "pattern": "^https://",
                        "description": "Public https URL; private and internal addresses are refused"
                      },
                      "caption": {
                        "type": "string"
                      },
                      "fileName": {
                        "type": "string"
                      },
                      "mimetype": {
                        "type": "string"
                      },
                      "ptt": {
                        "type": "boolean",
                        "description": "Push-to-talk (voice note) for audio"
                      },
                      "gifPlayback": {
                        "type": "boolean",
                        "description": "Play video as GIF"
                      }
                    },
                    "required": [
                      "type",
                      "url"
                    ]
                  }
                },
                "required": [
                  "name",
                  "body"
                ]
              },
              "example": {
                "name": "appointment_confirmation",
                "body": "Hi {{name}}, see you tomorrow at {{time}}."
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "templates:write"
            ]
          },
          {
            "apiKeyHeader": [
              "templates:write"
            ]
          }
        ],
        "responses": {
          "201": {
            "description": "The template.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The template.",
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "connectionId": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "name": {
                      "type": "string"
                    },
                    "body": {
                      "type": "string"
                    },
                    "media": {
                      "type": "object",
                      "properties": {
                        "type": {
                          "type": "string",
                          "enum": [
                            "image",
                            "video",
                            "audio",
                            "document",
                            "sticker"
                          ]
                        },
                        "url": {
                          "type": "string",
                          "format": "uri",
                          "pattern": "^https://",
                          "description": "Public https URL; private and internal addresses are refused"
                        },
                        "caption": {
                          "type": "string"
                        },
                        "fileName": {
                          "type": "string"
                        },
                        "mimetype": {
                          "type": "string"
                        },
                        "ptt": {
                          "type": "boolean",
                          "description": "Push-to-talk (voice note) for audio"
                        },
                        "gifPlayback": {
                          "type": "boolean",
                          "description": "Play video as GIF"
                        }
                      },
                      "required": [
                        "type",
                        "url"
                      ]
                    },
                    "createdAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "updatedAt": {
                      "type": "string",
                      "format": "date-time"
                    }
                  }
                },
                "example": {
                  "id": "7a0b3c4d-5e6f-4a7b-8c9d-2e3f4a5b6c7d",
                  "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                  "name": "appointment_confirmation",
                  "body": "Hi {{name}}, see you tomorrow at {{time}}.",
                  "createdAt": "2026-09-20T12:00:00.000Z",
                  "updatedAt": "2026-09-20T12:00:00.000Z"
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "description": "Conflict",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      },
      "get": {
        "operationId": "listTemplates",
        "summary": "Listar os templates",
        "tags": [
          "Templates"
        ],
        "description": "Todos os templates de uma conexão.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The connection's templates.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The connection's templates.",
                  "type": "object",
                  "properties": {
                    "templates": {
                      "type": "array"
                    },
                    "count": {
                      "type": "number"
                    }
                  }
                },
                "example": {
                  "templates": [
                    {
                      "id": "7a0b3c4d-5e6f-4a7b-8c9d-2e3f4a5b6c7d",
                      "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                      "name": "appointment_confirmation",
                      "body": "Hi {{name}}, see you tomorrow at {{time}}.",
                      "createdAt": "2026-09-20T12:00:00.000Z",
                      "updatedAt": "2026-09-20T12:00:00.000Z"
                    }
                  ],
                  "count": 1
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/connections/{id}/templates/{name}": {
      "get": {
        "operationId": "getTemplate",
        "summary": "Consultar um template pelo nome",
        "tags": [
          "Templates"
        ],
        "description": "Os detalhes do template, com as variáveis extraídas.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string"
            },
            "in": "path",
            "name": "name",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "connections:read"
            ]
          },
          {
            "apiKeyHeader": [
              "connections:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The template and the variables its body uses.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The template and the variables its body uses.",
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "connectionId": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "name": {
                      "type": "string"
                    },
                    "body": {
                      "type": "string"
                    },
                    "variables": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "name": {
                            "type": "string"
                          },
                          "required": {
                            "type": "boolean"
                          }
                        }
                      }
                    },
                    "createdAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "updatedAt": {
                      "type": "string",
                      "format": "date-time"
                    }
                  }
                },
                "example": {
                  "id": "7a0b3c4d-5e6f-4a7b-8c9d-2e3f4a5b6c7d",
                  "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                  "name": "appointment_confirmation",
                  "body": "Hi {{name}}, see you tomorrow at {{time}}.",
                  "createdAt": "2026-09-20T12:00:00.000Z",
                  "updatedAt": "2026-09-20T12:00:00.000Z",
                  "variables": [
                    {
                      "name": "name",
                      "required": true
                    },
                    {
                      "name": "time",
                      "required": true
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      },
      "put": {
        "operationId": "updateTemplate",
        "summary": "Atualizar um template",
        "tags": [
          "Templates"
        ],
        "description": "Atualiza o corpo e/ou a mídia do template. Envie media como null para removê-la.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "body": {
                    "type": "string"
                  },
                  "media": {
                    "type": [
                      "object",
                      "null"
                    ],
                    "properties": {
                      "type": {
                        "type": "string",
                        "enum": [
                          "image",
                          "video",
                          "audio",
                          "document",
                          "sticker"
                        ]
                      },
                      "url": {
                        "type": "string",
                        "format": "uri",
                        "pattern": "^https://",
                        "description": "Public https URL; private and internal addresses are refused"
                      },
                      "caption": {
                        "type": "string"
                      },
                      "fileName": {
                        "type": "string"
                      },
                      "mimetype": {
                        "type": "string"
                      },
                      "ptt": {
                        "type": "boolean",
                        "description": "Push-to-talk (voice note) for audio"
                      },
                      "gifPlayback": {
                        "type": "boolean",
                        "description": "Play video as GIF"
                      }
                    },
                    "required": [
                      "type",
                      "url"
                    ]
                  }
                }
              },
              "example": {
                "body": "Hi {{name}}, see you tomorrow at {{time}}. Reply YES to confirm."
              }
            }
          }
        },
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string"
            },
            "in": "path",
            "name": "name",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "templates:write"
            ]
          },
          {
            "apiKeyHeader": [
              "templates:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The updated template.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The updated template.",
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "name": {
                      "type": "string"
                    },
                    "body": {
                      "type": "string"
                    },
                    "updatedAt": {
                      "type": "string",
                      "format": "date-time"
                    }
                  }
                },
                "example": {
                  "id": "7a0b3c4d-5e6f-4a7b-8c9d-2e3f4a5b6c7d",
                  "name": "appointment_confirmation",
                  "body": "Hi {{name}}, see you tomorrow at {{time}}. Reply YES to confirm.",
                  "updatedAt": "2026-09-24T12:00:00.000Z"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      },
      "delete": {
        "operationId": "deleteTemplate",
        "summary": "Excluir um template",
        "tags": [
          "Templates"
        ],
        "parameters": [
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          },
          {
            "schema": {
              "type": "string"
            },
            "in": "path",
            "name": "name",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "templates:write"
            ]
          },
          {
            "apiKeyHeader": [
              "templates:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Deleted.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Deleted.",
                  "type": "object",
                  "properties": {
                    "deleted": {
                      "type": "boolean"
                    }
                  }
                },
                "example": {
                  "deleted": true
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        },
        "description": "Exclui o template da conexão."
      }
    },
    "/tenants/{id}/usage": {
      "get": {
        "operationId": "getTenantUsage",
        "summary": "Consultar o uso de um projeto",
        "tags": [
          "Usage"
        ],
        "description": "Mensagens enviadas hoje e neste mês (dias em UTC) pelo projeto e pela organização dele: os planos são da organização, e todos os projetos dela contam para os limites diário e mensal (os envios são recusados com 429 quando o uso da organização passa deles). Traz também a assinatura da organização e o histórico diário do projeto nos últimos `days` dias (padrão 30, no máximo 366).",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "default": "30"
            },
            "in": "query",
            "name": "days",
            "required": false
          },
          {
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "usage:read"
            ]
          },
          {
            "apiKeyHeader": [
              "usage:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The tenant's usage, and its organization's.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "The tenant's usage, and its organization's.",
                  "type": "object",
                  "properties": {
                    "tenantId": {
                      "type": "string"
                    },
                    "plan": {
                      "type": [
                        "object",
                        "null"
                      ],
                      "description": "The organization's plan; null: no limits",
                      "properties": {
                        "name": {
                          "type": "string"
                        },
                        "displayName": {
                          "type": "string"
                        },
                        "maxMessagesDay": {
                          "type": "number"
                        },
                        "maxMessagesMonth": {
                          "type": "number"
                        }
                      }
                    },
                    "usage": {
                      "type": "object",
                      "description": "The tenant's own messages, and their share of the organization's limits",
                      "properties": {
                        "today": {
                          "type": "number"
                        },
                        "thisMonth": {
                          "type": "number"
                        },
                        "percentOfDailyLimit": {
                          "type": "number"
                        },
                        "percentOfMonthlyLimit": {
                          "type": "number"
                        }
                      }
                    },
                    "organization": {
                      "type": "object",
                      "description": "The organization's messages (every tenant of it): what the limits are enforced on",
                      "properties": {
                        "id": {
                          "type": "string",
                          "format": "uuid"
                        },
                        "usage": {
                          "type": "object",
                          "properties": {
                            "today": {
                              "type": "number"
                            },
                            "thisMonth": {
                              "type": "number"
                            },
                            "percentOfDailyLimit": {
                              "type": "number"
                            },
                            "percentOfMonthlyLimit": {
                              "type": "number"
                            }
                          }
                        }
                      }
                    },
                    "subscription": {
                      "type": "object",
                      "description": "The organization's subscription",
                      "properties": {
                        "status": {
                          "type": "string"
                        },
                        "trialEndsAt": {
                          "type": [
                            "string",
                            "null"
                          ]
                        },
                        "currentPeriodEnd": {
                          "type": [
                            "string",
                            "null"
                          ]
                        }
                      }
                    },
                    "dailyUsage": {
                      "type": "array",
                      "description": "The tenant's",
                      "items": {
                        "type": "object",
                        "properties": {
                          "date": {
                            "type": "string"
                          },
                          "messagesSent": {
                            "type": "number"
                          },
                          "messagesRecv": {
                            "type": "number"
                          }
                        }
                      }
                    }
                  }
                },
                "example": {
                  "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                  "plan": {
                    "name": "pro",
                    "displayName": "Pro",
                    "maxMessagesDay": 1000,
                    "maxMessagesMonth": 20000
                  },
                  "usage": {
                    "today": 12,
                    "thisMonth": 540,
                    "percentOfDailyLimit": 1.2,
                    "percentOfMonthlyLimit": 2.7
                  },
                  "organization": {
                    "id": "2d5e8a1b-4c7f-4e9a-8b3d-6f0a2c4e8b1d",
                    "usage": {
                      "today": 30,
                      "thisMonth": 1200,
                      "percentOfDailyLimit": 3,
                      "percentOfMonthlyLimit": 6
                    }
                  },
                  "subscription": {
                    "status": "active",
                    "trialEndsAt": null,
                    "currentPeriodEnd": "2026-10-24T12:00:00.000Z"
                  },
                  "dailyUsage": [
                    {
                      "date": "2026-09-23",
                      "messagesSent": 42,
                      "messagesRecv": 17
                    },
                    {
                      "date": "2026-09-24",
                      "messagesSent": 12,
                      "messagesRecv": 5
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/messages": {
      "get": {
        "operationId": "listMessages",
        "summary": "Listar as mensagens registradas",
        "tags": [
          "Logs"
        ],
        "description": "Mensagens enfileiradas, enviadas e recebidas, das mais novas para as mais antigas. counts aplica todos os filtros exceto direction, para dimensionar as abas de direção.",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "enum": [
                "in",
                "out"
              ]
            },
            "in": "query",
            "name": "direction",
            "required": false
          },
          {
            "schema": {
              "type": "string",
              "enum": [
                "queued",
                "sent",
                "delivered",
                "read",
                "failed",
                "received"
              ]
            },
            "in": "query",
            "name": "status",
            "required": false
          },
          {
            "schema": {
              "type": "string"
            },
            "in": "query",
            "name": "tenantId",
            "required": false
          },
          {
            "schema": {
              "type": "string"
            },
            "in": "query",
            "name": "connectionId",
            "required": false
          },
          {
            "schema": {
              "type": "string"
            },
            "in": "query",
            "name": "q",
            "required": false,
            "description": "Contact, text, job id, clientRef or message id (case-insensitive)"
          },
          {
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 60
            },
            "in": "query",
            "name": "limit",
            "required": false,
            "description": "Capped at 200"
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "logs:read"
            ]
          },
          {
            "apiKeyHeader": [
              "logs:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Logged messages, newest first.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Logged messages, newest first.",
                  "type": "object",
                  "properties": {
                    "messages": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string"
                          },
                          "tenantId": {
                            "type": "string"
                          },
                          "connectionId": {
                            "type": "string"
                          },
                          "direction": {
                            "type": "string",
                            "enum": [
                              "in",
                              "out"
                            ]
                          },
                          "contact": {
                            "type": "string"
                          },
                          "type": {
                            "type": "string"
                          },
                          "body": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "status": {
                            "type": "string"
                          },
                          "jobId": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "clientRef": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "messageId": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "error": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "events": {
                            "type": "array",
                            "items": {
                              "type": "object",
                              "properties": {
                                "status": {
                                  "type": "string"
                                },
                                "at": {
                                  "type": "string",
                                  "format": "date-time"
                                }
                              }
                            }
                          },
                          "createdAt": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "updatedAt": {
                            "type": "string",
                            "format": "date-time"
                          }
                        }
                      }
                    },
                    "counts": {
                      "type": "object",
                      "properties": {
                        "all": {
                          "type": "number"
                        },
                        "in": {
                          "type": "number"
                        },
                        "out": {
                          "type": "number"
                        }
                      }
                    }
                  }
                },
                "example": {
                  "messages": [
                    {
                      "id": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
                      "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                      "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                      "direction": "out",
                      "contact": "5511988887777",
                      "type": "text",
                      "body": "Your appointment is confirmed for tomorrow at 10:00",
                      "status": "delivered",
                      "jobId": "c2a4e6f8-1b3d-4f5a-8c7e-9d0b1a2c3e4f",
                      "clientRef": "crm-msg-1",
                      "messageId": "3EB0C767D26A1D8A3F52",
                      "error": null,
                      "events": [
                        {
                          "status": "queued",
                          "at": "2026-09-24T11:59:55.000Z"
                        },
                        {
                          "status": "sent",
                          "at": "2026-09-24T12:00:00.000Z"
                        },
                        {
                          "status": "delivered",
                          "at": "2026-09-24T12:00:02.000Z"
                        }
                      ],
                      "createdAt": "2026-09-24T11:59:55.000Z",
                      "updatedAt": "2026-09-24T12:00:02.000Z"
                    }
                  ],
                  "counts": {
                    "all": 1,
                    "in": 0,
                    "out": 1
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/webhooks/deliveries": {
      "get": {
        "operationId": "listWebhookDeliveries",
        "summary": "Listar as entregas de webhook",
        "tags": [
          "Logs"
        ],
        "description": "Uma linha por evento de webhook, das mais novas para as mais antigas. counts ignora o filtro de estado; stats cobre todas as linhas retidas (successRate de 0 a 100, avgLatencyMs sobre as entregues).",
        "parameters": [
          {
            "schema": {
              "type": "string",
              "enum": [
                "delivered",
                "retry",
                "dead"
              ]
            },
            "in": "query",
            "name": "state",
            "required": false
          },
          {
            "schema": {
              "type": "string"
            },
            "in": "query",
            "name": "tenantId",
            "required": false
          },
          {
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 60
            },
            "in": "query",
            "name": "limit",
            "required": false,
            "description": "Capped at 200"
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "logs:read"
            ]
          },
          {
            "apiKeyHeader": [
              "logs:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Webhook deliveries, newest first.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Webhook deliveries, newest first.",
                  "type": "object",
                  "properties": {
                    "deliveries": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string"
                          },
                          "tenantId": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "connectionId": {
                            "type": "string"
                          },
                          "eventType": {
                            "type": "string"
                          },
                          "url": {
                            "type": "string"
                          },
                          "state": {
                            "type": "string",
                            "enum": [
                              "delivered",
                              "retry",
                              "dead"
                            ]
                          },
                          "httpStatus": {
                            "type": [
                              "number",
                              "null"
                            ]
                          },
                          "error": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "latencyMs": {
                            "type": [
                              "number",
                              "null"
                            ]
                          },
                          "attempts": {
                            "type": "number"
                          },
                          "maxAttempts": {
                            "type": "number"
                          },
                          "nextAttemptAt": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "format": "date-time"
                          },
                          "signed": {
                            "type": "boolean"
                          },
                          "payload": {},
                          "createdAt": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "updatedAt": {
                            "type": "string",
                            "format": "date-time"
                          }
                        }
                      }
                    },
                    "counts": {
                      "type": "object",
                      "properties": {
                        "all": {
                          "type": "number"
                        },
                        "delivered": {
                          "type": "number"
                        },
                        "retry": {
                          "type": "number"
                        },
                        "dead": {
                          "type": "number"
                        }
                      }
                    },
                    "stats": {
                      "type": "object",
                      "properties": {
                        "successRate": {
                          "type": [
                            "number",
                            "null"
                          ]
                        },
                        "avgLatencyMs": {
                          "type": [
                            "number",
                            "null"
                          ]
                        }
                      }
                    }
                  }
                },
                "example": {
                  "deliveries": [
                    {
                      "id": "9c2d5e6f-7a8b-4c9d-8e0f-3a4b5c6d7e8f",
                      "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                      "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                      "eventType": "message.delivery",
                      "url": "https://crm.example.com/api/whatsapp/events",
                      "state": "delivered",
                      "httpStatus": 200,
                      "error": null,
                      "latencyMs": 120,
                      "attempts": 1,
                      "maxAttempts": 6,
                      "nextAttemptAt": null,
                      "signed": true,
                      "payload": {
                        "type": "message.delivery",
                        "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                        "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                        "externalId": "shop-42",
                        "timestamp": "2026-09-24T12:00:02.000Z",
                        "data": {
                          "messageId": "3EB0C767D26A1D8A3F52",
                          "status": "delivered",
                          "recipient": "5511988887777",
                          "jid": "5511988887777@s.whatsapp.net",
                          "phone": "+5511988887777",
                          "clientRef": "crm-msg-1"
                        }
                      },
                      "createdAt": "2026-09-24T12:00:02.000Z",
                      "updatedAt": "2026-09-24T12:00:02.000Z"
                    }
                  ],
                  "counts": {
                    "all": 1,
                    "delivered": 1,
                    "retry": 0,
                    "dead": 0
                  },
                  "stats": {
                    "successRate": 100,
                    "avgLatencyMs": 120
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/webhooks/deliveries/resend-dead": {
      "post": {
        "operationId": "resendDeadWebhookDeliveries",
        "summary": "Reenviar todas as entregas de webhook mortas",
        "tags": [
          "Logs"
        ],
        "description": "Enfileira de novo todas as entregas no estado dead dos projetos de quem chama (de todos os projetos, para a plataforma; no máximo 1000 por chamada).",
        "security": [
          {
            "apiKeyBearer": [
              "webhooks:write"
            ]
          },
          {
            "apiKeyHeader": [
              "webhooks:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "How many deliveries were queued again.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "How many deliveries were queued again.",
                  "type": "object",
                  "properties": {
                    "requeued": {
                      "type": "number"
                    }
                  }
                },
                "example": {
                  "requeued": 3
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/webhooks/deliveries/{id}/resend": {
      "post": {
        "operationId": "resendWebhookDelivery",
        "summary": "Reenviar uma entrega de webhook",
        "tags": [
          "Logs"
        ],
        "description": "Enfileira a entrega de novo, para agora, com um novo limite de tentativas. Serve para entregas mortas (dead) e em nova tentativa (retry); uma já entregue responde 409.",
        "parameters": [
          {
            "schema": {
              "type": "string"
            },
            "in": "path",
            "name": "id",
            "required": true
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "webhooks:write"
            ]
          },
          {
            "apiKeyHeader": [
              "webhooks:write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The delivery, queued again.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "tenantId": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "connectionId": {
                      "type": "string"
                    },
                    "eventType": {
                      "type": "string"
                    },
                    "url": {
                      "type": "string"
                    },
                    "state": {
                      "type": "string",
                      "enum": [
                        "delivered",
                        "retry",
                        "dead"
                      ]
                    },
                    "httpStatus": {
                      "type": [
                        "number",
                        "null"
                      ]
                    },
                    "error": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "latencyMs": {
                      "type": [
                        "number",
                        "null"
                      ]
                    },
                    "attempts": {
                      "type": "number"
                    },
                    "maxAttempts": {
                      "type": "number"
                    },
                    "nextAttemptAt": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time"
                    },
                    "signed": {
                      "type": "boolean"
                    },
                    "payload": {},
                    "createdAt": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "updatedAt": {
                      "type": "string",
                      "format": "date-time"
                    }
                  },
                  "description": "The delivery, queued again."
                },
                "example": {
                  "id": "9c2d5e6f-7a8b-4c9d-8e0f-3a4b5c6d7e8f",
                  "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                  "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                  "eventType": "message.delivery",
                  "url": "https://crm.example.com/api/whatsapp/events",
                  "state": "retry",
                  "httpStatus": 500,
                  "error": "HTTP 500",
                  "latencyMs": 80,
                  "attempts": 0,
                  "maxAttempts": 6,
                  "nextAttemptAt": "2026-09-24T12:00:00.000Z",
                  "signed": true,
                  "payload": {
                    "type": "message.delivery",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:02.000Z",
                    "data": {
                      "messageId": "3EB0C767D26A1D8A3F52",
                      "status": "delivered",
                      "recipient": "5511988887777",
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777",
                      "clientRef": "crm-msg-1"
                    }
                  },
                  "createdAt": "2026-09-24T12:00:02.000Z",
                  "updatedAt": "2026-09-24T12:00:02.000Z"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "409": {
            "description": "Conflict",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string"
                    },
                    "missingVariables": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  },
                  "required": [
                    "error"
                  ]
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    },
    "/usage/daily": {
      "get": {
        "operationId": "getDailyUsage",
        "summary": "Totais diários de mensagens dos projetos de quem chama (de todos, para a plataforma)",
        "tags": [
          "Usage"
        ],
        "description": "Uma entrada por dia em UTC, incluindo os dias zerados, do mais antigo ao mais recente; hoje é a última.",
        "parameters": [
          {
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 90,
              "default": 14
            },
            "in": "query",
            "name": "days",
            "required": false
          }
        ],
        "security": [
          {
            "apiKeyBearer": [
              "usage:read"
            ]
          },
          {
            "apiKeyHeader": [
              "usage:read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Daily totals, oldest first.",
            "content": {
              "application/json": {
                "schema": {
                  "description": "Daily totals, oldest first.",
                  "type": "object",
                  "properties": {
                    "days": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "date": {
                            "type": "string",
                            "description": "YYYY-MM-DD (UTC)"
                          },
                          "sent": {
                            "type": "number"
                          },
                          "received": {
                            "type": "number"
                          }
                        }
                      }
                    }
                  }
                },
                "example": {
                  "days": [
                    {
                      "date": "2026-09-23",
                      "sent": 42,
                      "received": 17
                    },
                    {
                      "date": "2026-09-24",
                      "sent": 12,
                      "received": 5
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        }
      }
    }
  },
  "servers": [
    {
      "url": "https://api.apiwpp.com",
      "description": "This gateway"
    }
  ],
  "webhooks": {
    "connection.status": {
      "post": {
        "operationId": "onConnectionStatus",
        "tags": [
          "Webhooks"
        ],
        "summary": "A conexão abriu, fechou ou foi restringida",
        "description": "data de connection.status: o socket abriu ou fechou, ou o WhatsApp mudou o que a conta pode fazer. Um fechamento informado pelo gateway traz o motivo (reason) e se o gateway reconecta sozinho (willReconnect). willReconnect true (transient, restart_required) quer dizer que o gateway continua tentando, com espera crescente, até abrir de novo, o que o próximo status open informa; false quer dizer que ele parou e espera alguém: um QR novo (logged_out, qr_not_scanned) ou uma reconexão explícita (replaced, manual). passkey_required: o QR foi escaneado, mas o pareamento não terminou porque o WhatsApp pediu uma passkey (chave de acesso) ao celular; status é close, não há phoneNumber (a conexão nunca confirmou um) e nenhum QR code novo é gerado até a conexão ser conectada de novo. reachout_timelock: o WhatsApp colocou a conta sob um bloqueio temporário de novas conversas (reach-out timelock; enviado depois de um erro 463 ou de uma notificação do WhatsApp; status é o atual, normalmente open); até reachoutTimelock.endsAt (ou um evento reachout_timelock_lifted), todo envio da fila é descartado como message.send_failed com reason reachout_timelocked, sem ser tentado. reason não vem numa abertura; willReconnect e statusCode só vêm num fechamento com um dos seis primeiros motivos.\n\nEntregue pelo menos uma vez: aplique-o de forma idempotente.",
        "parameters": [
          {
            "$ref": "#/components/parameters/WebhookToken"
          },
          {
            "$ref": "#/components/parameters/WebhookTimestamp"
          },
          {
            "$ref": "#/components/parameters/WebhookSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/WebhookEventEnvelope"
                  },
                  {
                    "type": "object",
                    "properties": {
                      "type": {
                        "const": "connection.status"
                      },
                      "data": {
                        "$ref": "#/components/schemas/ConnectionStatusEvent"
                      }
                    }
                  }
                ]
              },
              "examples": {
                "example1": {
                  "summary": "Opened",
                  "value": {
                    "type": "connection.status",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "status": "open",
                      "phoneNumber": "5511900000001"
                    }
                  }
                },
                "example2": {
                  "summary": "Closed, reconnecting on its own",
                  "value": {
                    "type": "connection.status",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "status": "close",
                      "phoneNumber": "5511900000001",
                      "reason": "transient",
                      "willReconnect": true,
                      "statusCode": 503
                    }
                  }
                },
                "example3": {
                  "summary": "Logged out on the phone",
                  "value": {
                    "type": "connection.status",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "status": "close",
                      "phoneNumber": "5511900000001",
                      "reason": "logged_out",
                      "willReconnect": false,
                      "statusCode": 401
                    }
                  }
                },
                "example4": {
                  "summary": "Reach-out timelock",
                  "value": {
                    "type": "connection.status",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "status": "open",
                      "phoneNumber": "5511900000001",
                      "reason": "reachout_timelock",
                      "reachoutTimelock": {
                        "active": true,
                        "endsAt": "2026-09-25T12:00:00.000Z",
                        "enforcementType": "BIZ_QUALITY"
                      }
                    }
                  }
                },
                "example5": {
                  "summary": "Pairing stalled on a passkey",
                  "value": {
                    "type": "connection.status",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "status": "close",
                      "reason": "passkey_required"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Delivered. The response body is ignored."
          },
          "3XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "4XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "5XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          }
        },
        "security": []
      }
    },
    "message.incoming": {
      "post": {
        "operationId": "onMessageIncoming",
        "tags": [
          "Webhooks"
        ],
        "summary": "Alguém escreveu para o número",
        "description": "data de message.incoming: uma mensagem que alguém enviou ao número, numa conversa individual ou num grupo de que ele participa (nesse caso, jid é o grupo e phone é null).\n\nEntregue pelo menos uma vez: aplique-o de forma idempotente.",
        "parameters": [
          {
            "$ref": "#/components/parameters/WebhookToken"
          },
          {
            "$ref": "#/components/parameters/WebhookTimestamp"
          },
          {
            "$ref": "#/components/parameters/WebhookSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/WebhookEventEnvelope"
                  },
                  {
                    "type": "object",
                    "properties": {
                      "type": {
                        "const": "message.incoming"
                      },
                      "data": {
                        "$ref": "#/components/schemas/MessageIncomingEvent"
                      }
                    }
                  }
                ]
              },
              "examples": {
                "example1": {
                  "summary": "Text",
                  "value": {
                    "type": "message.incoming",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "from": "5511988887777@s.whatsapp.net",
                      "to": "5511900000001:7@s.whatsapp.net",
                      "body": "Olá! Tem horário amanhã às 10h?",
                      "timestamp": 1790251200,
                      "raw": {
                        "key": {
                          "remoteJid": "5511988887777@s.whatsapp.net",
                          "fromMe": false,
                          "id": "IN-TEXT-1"
                        },
                        "message": {
                          "conversation": "Olá! Tem horário amanhã às 10h?"
                        },
                        "messageTimestamp": 1790251200,
                        "pushName": "Maria"
                      },
                      "resolvedPhone": "5511988887777",
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777"
                    }
                  }
                },
                "example2": {
                  "summary": "Image with a signed media URL",
                  "value": {
                    "type": "message.incoming",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "from": "5511988887777@s.whatsapp.net",
                      "to": "5511900000001:7@s.whatsapp.net",
                      "body": "Is this haircut possible?",
                      "timestamp": 1790251200,
                      "raw": {
                        "key": {
                          "remoteJid": "5511988887777@s.whatsapp.net",
                          "fromMe": false,
                          "id": "IN-IMG-1"
                        }
                      },
                      "media": {
                        "type": "image",
                        "url": "https://gateway.example.com/media/8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f/IN-IMG-1.jpg?exp=1790337600&sig=zPUxL8vvbncrSGOkg72U9hOK-6GOcrWOlHSYjjv4sHs",
                        "mimetype": "image/jpeg",
                        "fileName": "IN-IMG-1.jpg",
                        "fileSize": 48213,
                        "expiresAt": 1790337600000
                      },
                      "resolvedPhone": "5511988887777",
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777"
                    }
                  }
                },
                "example3": {
                  "summary": "From a LID not resolved yet (see contact.resolved)",
                  "value": {
                    "type": "message.incoming",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "from": "11122233344455@lid",
                      "to": "5511900000001:7@s.whatsapp.net",
                      "body": "Can I bring my son too?",
                      "timestamp": 1790251200,
                      "raw": {
                        "key": {
                          "remoteJid": "11122233344455@lid",
                          "fromMe": false,
                          "id": "IN-TEXT-2"
                        }
                      },
                      "jid": "11122233344455@lid",
                      "phone": null
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Delivered. The response body is ignored."
          },
          "3XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "4XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "5XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          }
        },
        "security": []
      }
    },
    "message.outgoing": {
      "post": {
        "operationId": "onMessageOutgoing",
        "tags": [
          "Webhooks"
        ],
        "summary": "O número enviou uma mensagem (opcional: emitOutgoing)",
        "description": "data de message.outgoing: uma mensagem que o número pareado enviou numa conversa individual. Emitido uma vez por messageId, e só para um projeto criado ou atualizado com emitOutgoing: true (desligado por padrão). origin API = o gateway a enviou por POST /connections/:id/send (o id foi registrado antes do envio, então é uma consulta, nunca um palpite); origin PHONE = digitada no celular ou em outro aparelho conectado. Grupos, status e canais não são informados.\n\nEntregue pelo menos uma vez: aplique-o de forma idempotente.",
        "parameters": [
          {
            "$ref": "#/components/parameters/WebhookToken"
          },
          {
            "$ref": "#/components/parameters/WebhookTimestamp"
          },
          {
            "$ref": "#/components/parameters/WebhookSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/WebhookEventEnvelope"
                  },
                  {
                    "type": "object",
                    "properties": {
                      "type": {
                        "const": "message.outgoing"
                      },
                      "data": {
                        "$ref": "#/components/schemas/MessageOutgoingEvent"
                      }
                    }
                  }
                ]
              },
              "examples": {
                "example1": {
                  "summary": "Sent through the API",
                  "value": {
                    "type": "message.outgoing",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "messageId": "3EB0C767D26A1D8A3F52",
                      "origin": "API",
                      "clientRef": "crm-msg-1",
                      "to": "5511988887777@s.whatsapp.net",
                      "toE164": "+5511988887777",
                      "body": "Your appointment is confirmed for tomorrow at 10:00",
                      "timestamp": 1790251200,
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777"
                    }
                  }
                },
                "example2": {
                  "summary": "Typed on the phone",
                  "value": {
                    "type": "message.outgoing",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "messageId": "3EB0A1B2C3D4E5F60718",
                      "origin": "PHONE",
                      "clientRef": null,
                      "to": "5511988887777@s.whatsapp.net",
                      "toE164": "+5511988887777",
                      "body": "See you tomorrow!",
                      "timestamp": 1790251200,
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Delivered. The response body is ignored."
          },
          "3XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "4XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "5XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          }
        },
        "security": []
      }
    },
    "message.delivery": {
      "post": {
        "operationId": "onMessageDelivery",
        "tags": [
          "Webhooks"
        ],
        "summary": "Uma mensagem enviada pelo número mudou de status",
        "description": "data de message.delivery: uma mudança de status de uma mensagem que o número enviou.\n\nEntregue pelo menos uma vez: aplique-o de forma idempotente.",
        "parameters": [
          {
            "$ref": "#/components/parameters/WebhookToken"
          },
          {
            "$ref": "#/components/parameters/WebhookTimestamp"
          },
          {
            "$ref": "#/components/parameters/WebhookSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/WebhookEventEnvelope"
                  },
                  {
                    "type": "object",
                    "properties": {
                      "type": {
                        "const": "message.delivery"
                      },
                      "data": {
                        "$ref": "#/components/schemas/MessageDeliveryEvent"
                      }
                    }
                  }
                ]
              },
              "examples": {
                "example1": {
                  "summary": "Delivered",
                  "value": {
                    "type": "message.delivery",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "messageId": "3EB0C767D26A1D8A3F52",
                      "status": "delivered",
                      "recipient": "5511988887777",
                      "clientRef": "crm-msg-1",
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777"
                    }
                  }
                },
                "example2": {
                  "summary": "Refused as a reach-out (463)",
                  "value": {
                    "type": "message.delivery",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "messageId": "3EB0C767D26A1D8A3F52",
                      "status": "failed",
                      "recipient": "5511988887777",
                      "clientRef": "crm-msg-1",
                      "reason": "reachout_timelocked",
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Delivered. The response body is ignored."
          },
          "3XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "4XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "5XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          }
        },
        "security": []
      }
    },
    "message.send_failed": {
      "post": {
        "operationId": "onMessageSendFailed",
        "tags": [
          "Webhooks"
        ],
        "summary": "Um envio na fila com clientRef não vai acontecer",
        "description": "data de message.send_failed: um job enfileirado por POST /connections/:id/send COM um clientRef do qual o gateway desistiu (tentativas esgotadas, a reserva dele expirou na última tentativa, o número não está no WhatsApp, ou a conta está sob um bloqueio temporário de novas conversas do WhatsApp e o envio foi recusado sem ser tentado). Nunca é emitido para um job sem clientRef. Uma nova tentativa com o mesmo clientRef continua respondendo duplicate, então este é o único sinal, para o consumidor, de que o envio aceito não vai acontecer; um reenvio deliberado usa um clientRef novo. Se um eco ou um status de entrega do mesmo clientRef chegar depois, essa prova prevalece.\n\nEntregue pelo menos uma vez: aplique-o de forma idempotente.",
        "parameters": [
          {
            "$ref": "#/components/parameters/WebhookToken"
          },
          {
            "$ref": "#/components/parameters/WebhookTimestamp"
          },
          {
            "$ref": "#/components/parameters/WebhookSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/WebhookEventEnvelope"
                  },
                  {
                    "type": "object",
                    "properties": {
                      "type": {
                        "const": "message.send_failed"
                      },
                      "data": {
                        "$ref": "#/components/schemas/MessageSendFailedEvent"
                      }
                    }
                  }
                ]
              },
              "examples": {
                "example1": {
                  "summary": "Not on WhatsApp",
                  "value": {
                    "type": "message.send_failed",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "clientRef": "crm-msg-1",
                      "jobId": "c2a4e6f8-1b3d-4f5a-8c7e-9d0b1a2c3e4f",
                      "messageId": null,
                      "to": "5511988887777",
                      "reason": "not_on_whatsapp",
                      "attempts": 1,
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Delivered. The response body is ignored."
          },
          "3XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "4XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "5XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          }
        },
        "security": []
      }
    },
    "message.reaction": {
      "post": {
        "operationId": "onMessageReaction",
        "tags": [
          "Webhooks"
        ],
        "summary": "Alguém reagiu a uma mensagem",
        "description": "data de message.reaction.\n\nEntregue pelo menos uma vez: aplique-o de forma idempotente.",
        "parameters": [
          {
            "$ref": "#/components/parameters/WebhookToken"
          },
          {
            "$ref": "#/components/parameters/WebhookTimestamp"
          },
          {
            "$ref": "#/components/parameters/WebhookSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/WebhookEventEnvelope"
                  },
                  {
                    "type": "object",
                    "properties": {
                      "type": {
                        "const": "message.reaction"
                      },
                      "data": {
                        "$ref": "#/components/schemas/MessageReactionEvent"
                      }
                    }
                  }
                ]
              },
              "examples": {
                "example1": {
                  "summary": "Reaction added",
                  "value": {
                    "type": "message.reaction",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "messageId": "3EB0C767D26A1D8A3F52",
                      "from": "5511988887777",
                      "emoji": "👍",
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777"
                    }
                  }
                },
                "example2": {
                  "summary": "Reaction removed",
                  "value": {
                    "type": "message.reaction",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "messageId": "3EB0C767D26A1D8A3F52",
                      "from": "5511988887777",
                      "emoji": "",
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Delivered. The response body is ignored."
          },
          "3XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "4XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "5XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          }
        },
        "security": []
      }
    },
    "contact.resolved": {
      "post": {
        "operationId": "onContactResolved",
        "tags": [
          "Webhooks"
        ],
        "summary": "Um remetente conhecido só pelo LID agora tem telefone",
        "description": "data de contact.resolved. Um remetente que antes chegou a este projeto como LID, com phone: null, agora tem um número de telefone conhecido. Emitido uma vez por LID pendente por conexão, só para o projeto que recebeu aquelas mensagens. Reatribua todos os eventos anteriores cujo jid seja igual a data.lid.\n\nEntregue pelo menos uma vez: aplique-o de forma idempotente.",
        "parameters": [
          {
            "$ref": "#/components/parameters/WebhookToken"
          },
          {
            "$ref": "#/components/parameters/WebhookTimestamp"
          },
          {
            "$ref": "#/components/parameters/WebhookSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/WebhookEventEnvelope"
                  },
                  {
                    "type": "object",
                    "properties": {
                      "type": {
                        "const": "contact.resolved"
                      },
                      "data": {
                        "$ref": "#/components/schemas/ContactResolvedEvent"
                      }
                    }
                  }
                ]
              },
              "examples": {
                "example1": {
                  "summary": "Resolved",
                  "value": {
                    "type": "contact.resolved",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "lid": "11122233344455@lid",
                      "jid": "5511988887777@s.whatsapp.net",
                      "phone": "+5511988887777",
                      "firstSeenAt": "2026-09-24T12:00:00.000Z",
                      "messageCount": 2,
                      "source": "lid-mapping"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Delivered. The response body is ignored."
          },
          "3XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "4XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "5XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          }
        },
        "security": []
      }
    },
    "group.joined": {
      "post": {
        "operationId": "onGroupJoined",
        "tags": [
          "Webhooks"
        ],
        "summary": "O número entrou num grupo",
        "description": "data de group.joined: o número entrou ou foi adicionado a um grupo. Também é enviado uma vez por grupo de que o número já participa quando a conexão dele abre pela primeira vez neste processo do gateway (não de novo nas reconexões).\n\nEntregue pelo menos uma vez: aplique-o de forma idempotente.",
        "parameters": [
          {
            "$ref": "#/components/parameters/WebhookToken"
          },
          {
            "$ref": "#/components/parameters/WebhookTimestamp"
          },
          {
            "$ref": "#/components/parameters/WebhookSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/WebhookEventEnvelope"
                  },
                  {
                    "type": "object",
                    "properties": {
                      "type": {
                        "const": "group.joined"
                      },
                      "data": {
                        "$ref": "#/components/schemas/GroupJoinedEvent"
                      }
                    }
                  }
                ]
              },
              "examples": {
                "example1": {
                  "summary": "Joined",
                  "value": {
                    "type": "group.joined",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "groupId": "120363040000000001@g.us",
                      "groupName": "Barber team",
                      "participantCount": 3
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Delivered. The response body is ignored."
          },
          "3XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "4XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "5XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          }
        },
        "security": []
      }
    },
    "group.left": {
      "post": {
        "operationId": "onGroupLeft",
        "tags": [
          "Webhooks"
        ],
        "summary": "O número foi removido de um grupo",
        "description": "data de group.left: o número foi removido de um grupo.\n\nEntregue pelo menos uma vez: aplique-o de forma idempotente.",
        "parameters": [
          {
            "$ref": "#/components/parameters/WebhookToken"
          },
          {
            "$ref": "#/components/parameters/WebhookTimestamp"
          },
          {
            "$ref": "#/components/parameters/WebhookSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/WebhookEventEnvelope"
                  },
                  {
                    "type": "object",
                    "properties": {
                      "type": {
                        "const": "group.left"
                      },
                      "data": {
                        "$ref": "#/components/schemas/GroupLeftEvent"
                      }
                    }
                  }
                ]
              },
              "examples": {
                "example1": {
                  "summary": "Removed",
                  "value": {
                    "type": "group.left",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "groupId": "120363040000000001@g.us",
                      "reason": "kicked"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Delivered. The response body is ignored."
          },
          "3XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "4XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "5XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          }
        },
        "security": []
      }
    },
    "group.updated": {
      "post": {
        "operationId": "onGroupUpdated",
        "tags": [
          "Webhooks"
        ],
        "summary": "Um grupo do número mudou",
        "description": "data de group.updated: um grupo de que o número participa mudou.\n\nEntregue pelo menos uma vez: aplique-o de forma idempotente.",
        "parameters": [
          {
            "$ref": "#/components/parameters/WebhookToken"
          },
          {
            "$ref": "#/components/parameters/WebhookTimestamp"
          },
          {
            "$ref": "#/components/parameters/WebhookSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/WebhookEventEnvelope"
                  },
                  {
                    "type": "object",
                    "properties": {
                      "type": {
                        "const": "group.updated"
                      },
                      "data": {
                        "$ref": "#/components/schemas/GroupUpdatedEvent"
                      }
                    }
                  }
                ]
              },
              "examples": {
                "example1": {
                  "summary": "Renamed",
                  "value": {
                    "type": "group.updated",
                    "connectionId": "8b1d4e7f-2c3a-4f5b-9e6d-7a8b9c0d1e2f",
                    "tenantId": "3f6c2a8e-9d41-4b7a-8c15-2e7d9a0b4c61",
                    "externalId": "shop-42",
                    "timestamp": "2026-09-24T12:00:00.000Z",
                    "data": {
                      "groupId": "120363040000000001@g.us",
                      "groupName": "Barber team 2026"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Delivered. The response body is ignored."
          },
          "3XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "4XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          },
          "5XX": {
            "description": "A failed attempt, like a network error or no answer within 10 s (redirects are never followed). It is retried with backoff, 6 attempts in all, then dead-lettered: see GET /webhooks/deliveries to resend it."
          }
        },
        "security": []
      }
    }
  },
  "security": [
    {
      "apiKeyBearer": []
    },
    {
      "apiKeyHeader": []
    }
  ],
  "tags": [
    {
      "name": "Connections",
      "description": "Números de WhatsApp: liste-os, pareie por QR code, roteie-os pelo seu próprio proxy, desconecte, saia (logout).",
      "x-displayName": "Conexões"
    },
    {
      "name": "Messages",
      "description": "Enfileire mensagens e reações; consulte e cancele a fila de envio.",
      "x-displayName": "Mensagens"
    },
    {
      "name": "Contacts",
      "description": "Se números estão no WhatsApp, e perfis de contatos.",
      "x-displayName": "Contatos"
    },
    {
      "name": "Templates",
      "description": "Mensagens reutilizáveis com {{variáveis}}, por conexão.",
      "x-displayName": "Templates"
    },
    {
      "name": "Media",
      "description": "Arquivos de mídia recebidos, baixados pelas URLs assinadas que os webhooks trazem.",
      "x-displayName": "Mídia"
    },
    {
      "name": "Tenants",
      "description": "Seus projetos (tenants): configuração de webhook, as conexões deles e o histórico delas.",
      "x-displayName": "Projetos"
    },
    {
      "name": "API keys",
      "description": "As chaves de API de um projeto: criar (mostrada uma única vez), listar, revogar, rotacionar.",
      "x-displayName": "Chaves de API"
    },
    {
      "name": "Usage",
      "description": "Mensagens enviadas e recebidas, frente aos limites do plano.",
      "x-displayName": "Uso"
    },
    {
      "name": "Logs",
      "description": "Registro de mensagens e registro de entregas de webhook, com reenvio.",
      "x-displayName": "Registros"
    },
    {
      "name": "Account",
      "description": "A credencial que chama: a organização dela, os escopos que tem e os projetos a que chega.",
      "x-displayName": "Conta"
    },
    {
      "name": "Webhooks",
      "description": "Eventos que o gateway envia por POST ao webhookBaseUrl do projeto.",
      "x-displayName": "Webhooks"
    }
  ]
}
