openapi: 3.1.0
info:
  title: Atol Connect API
  version: "1.0.0"
  summary: API oficial do WhatsApp (Cloud API) para os seus sistemas.
  description: |
    Envie mensagens de WhatsApp, acompanhe o status de entrega e gerencie modelos a partir do seu ERP, PDV ou loja virtual.

    **Autenticação:** crie uma chave em *Painel → API e webhooks* e envie `Authorization: Bearer atol_live_...`.
    Cada chave tem escopos; chamadas contam na cota mensal do plano.

    **Regras do WhatsApp aplicadas:** texto livre só dentro da janela de 24h desde a última mensagem do cliente;
    fora dela, use um modelo aprovado. Contatos em opt-out (SAIR, PARAR, STOP, CANCELAR) não recebem modelos.

    As tarifas por mensagem são cobradas pela Meta diretamente na conta do WhatsApp Business do cliente.
  contact:
    name: Maldivas Tech
    email: suporte@maldivastech.dev
    url: https://connect.maldivastech.dev/docs
  termsOfService: https://maldivastech.dev/pt/termos
servers:
  - url: https://connect.maldivastech.dev/api/v1
security:
  - apiKey: []
tags:
  - name: Mensagens
  - name: Modelos
  - name: Números
paths:
  /messages:
    post:
      tags: [Mensagens]
      operationId: sendMessage
      summary: Enviar mensagem (modelo ou texto)
      description: Requer o escopo `messages:write`.
      parameters:
        - in: header
          name: Idempotency-Key
          required: false
          schema: { type: string, maxLength: 100 }
          description: Repetir a mesma chave em 24h devolve o resultado anterior sem reenviar.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SendMessageRequest" }
            examples:
              modelo:
                summary: Modelo aprovado com variáveis
                value:
                  to: "5511999999999"
                  type: template
                  template:
                    name: pedido_confirmado
                    language: pt_BR
                    components:
                      - type: body
                        parameters:
                          - { type: text, text: Maria }
                          - { type: text, text: "#1042" }
              texto:
                summary: Texto livre (janela de 24h)
                value:
                  to: "5511999999999"
                  type: text
                  text: { body: Seu pedido saiu para entrega. }
      responses:
        "201":
          description: Enviada para a Meta.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/SentMessage" }
                  idempotent_replay: { type: boolean }
        "400": { $ref: "#/components/responses/Error" }
        "401": { $ref: "#/components/responses/Error" }
        "402": { $ref: "#/components/responses/Error" }
        "403": { $ref: "#/components/responses/Error" }
        "409": { $ref: "#/components/responses/Error" }
        "422": { $ref: "#/components/responses/Error" }
        "429": { $ref: "#/components/responses/Error" }
        "502": { $ref: "#/components/responses/Error" }
    get:
      tags: [Mensagens]
      operationId: listMessages
      summary: Listar mensagens recentes
      description: Requer o escopo `messages:read`.
      parameters:
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
        - { in: query, name: before, schema: { type: string, format: date-time }, description: Paginação pelo campo created_at. }
      responses:
        "200":
          description: Mensagens, da mais recente para a mais antiga.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/Message" } }
        "401": { $ref: "#/components/responses/Error" }
  /messages/{wamid}:
    get:
      tags: [Mensagens]
      operationId: getMessage
      summary: Status de uma mensagem
      description: Requer o escopo `messages:read`.
      parameters:
        - { in: path, name: wamid, required: true, schema: { type: string } }
      responses:
        "200":
          description: Mensagem encontrada.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/Message" }
        "404": { $ref: "#/components/responses/Error" }
  /templates:
    get:
      tags: [Modelos]
      operationId: listTemplates
      summary: Listar modelos
      description: Requer o escopo `templates:read`.
      parameters:
        - in: query
          name: status
          schema: { type: string, enum: [APPROVED, PENDING, REJECTED, PAUSED, DISABLED] }
      responses:
        "200":
          description: Modelos da organização.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/Template" } }
    post:
      tags: [Modelos]
      operationId: createTemplate
      summary: Criar modelo e enviar para aprovação
      description: Requer o escopo `templates:write`. O resultado da análise chega pelo webhook `template.status`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CreateTemplateRequest" }
      responses:
        "201":
          description: Modelo criado com status PENDING (ou já APPROVED).
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/Template" }
        "409": { $ref: "#/components/responses/Error" }
        "422": { $ref: "#/components/responses/Error" }
  /phone-numbers:
    get:
      tags: [Números]
      operationId: listPhoneNumbers
      summary: Listar números conectados
      description: Requer o escopo `numbers:read`.
      responses:
        "200":
          description: Números ativos.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/PhoneNumber" } }
components:
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      bearerFormat: atol_live_*
  responses:
    Error:
      description: Erro.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
  schemas:
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code]
          properties:
            code:
              type: string
              enum: [invalid_body, unauthorized, forbidden, subscription_inactive, quota_exceeded, no_phone_number,
                     opted_out, outside_service_window, invalid_phone, not_connected, token_expired, meta_error,
                     not_found, internal_error]
            message: { type: string }
            details: {}
    SendMessageRequest:
      type: object
      required: [to, type]
      properties:
        to: { type: string, description: Telefone com DDI e DDD, só dígitos., example: "5511999999999" }
        phone_number_id: { type: string, description: Remetente quando houver mais de um número. }
        type: { type: string, enum: [text, template] }
        text:
          type: object
          required: [body]
          properties:
            body: { type: string, maxLength: 4096 }
            preview_url: { type: boolean }
        template:
          type: object
          required: [name, language]
          properties:
            name: { type: string }
            language: { type: string, example: pt_BR }
            components: { type: array, items: { type: object }, description: Mesmo formato da Cloud API da Meta. }
    SentMessage:
      type: object
      properties:
        id: { type: string, format: uuid }
        wamid: { type: string }
        conversation_id: { type: string, format: uuid }
        to: { type: string }
        status: { type: string, enum: [sent] }
    Message:
      type: object
      properties:
        id: { type: string, format: uuid }
        wamid: { type: string }
        direction: { type: string, enum: [inbound, outbound] }
        type: { type: string }
        text: { type: [string, "null"] }
        status: { type: string, enum: [queued, sent, delivered, read, failed, received] }
        error: {}
        created_at: { type: string, format: date-time }
        status_updated_at: { type: [string, "null"], format: date-time }
    Template:
      type: object
      properties:
        name: { type: string }
        language: { type: string }
        category: { type: string, enum: [MARKETING, UTILITY, AUTHENTICATION] }
        status: { type: string }
        components: { type: array, items: { type: object } }
        rejected_reason: { type: [string, "null"] }
        updated_at: { type: string, format: date-time }
    CreateTemplateRequest:
      type: object
      required: [name, language, category, components]
      properties:
        name: { type: string, pattern: "^[a-z0-9_]{1,512}$" }
        language: { type: string, example: pt_BR }
        category: { type: string, enum: [MARKETING, UTILITY, AUTHENTICATION] }
        components:
          type: array
          minItems: 1
          items: { type: object }
          example:
            - type: BODY
              text: "Olá {{1}}, seu pedido {{2}} foi confirmado."
              example: { body_text: [[Maria, "#1042"]] }
    PhoneNumber:
      type: object
      properties:
        phone_number_id: { type: string }
        display_phone_number: { type: string }
        verified_name: { type: string }
        quality_rating: { type: [string, "null"] }
        platform_type: { type: [string, "null"] }
        status: { type: string }
webhooks:
  message.received:
    post:
      summary: Mensagem recebida de um cliente
      parameters:
        - { in: header, name: X-Atol-Signature, required: true, schema: { type: string }, description: "sha256=HMAC(segredo, \"<timestamp>.<corpo>\")" }
        - { in: header, name: X-Atol-Timestamp, required: true, schema: { type: string } }
        - { in: header, name: X-Atol-Event, required: true, schema: { type: string } }
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                event: { const: message.received }
                created_at: { type: string, format: date-time }
                data:
                  type: object
                  properties:
                    wamid: { type: string }
                    from: { type: string }
                    profile_name: { type: string }
                    phone_number_id: { type: string }
                    type: { type: string }
                    text: { type: string }
                    timestamp: { type: string, format: date-time }
                    message: { type: object }
      responses:
        "200": { description: Recebido. Responda 2xx em até 10 s. }
  message.status:
    post:
      summary: Status de entrega ou leitura
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                event: { const: message.status }
                data:
                  type: object
                  properties:
                    wamid: { type: string }
                    status: { type: string, enum: [sent, delivered, read, failed] }
                    recipient: { type: string }
                    errors: { type: array, items: { type: object } }
                    pricing_category: { type: string }
      responses:
        "200": { description: Recebido. }
