{
  "openapi": "3.0.3",
  "info": {
    "title": "Trasty API",
    "version": "1.2.0",
    "description": "Consulta de observabilidade e tracking de WhatsApp (click/webhook) da Trasty"
  },
  "servers": [
    { "url": "https://api.trasty.io" }
  ],
  "components": {
    "securitySchemes": {
      "TrastyApiKey": {
        "type": "apiKey",
        "in": "header",
        "name": "X-Trasty-API-KEY",
        "description": "API Key do domínio/conta (header obrigatório)."
      }
    },
    "schemas": {
      "ErrorResponse": {
        "type": "object",
        "properties": {
          "error": { "type": "string", "example": "Not Authorized." }
        },
        "required": ["error"],
        "additionalProperties": false
      },

      "UsageBreakdownItem": {
        "type": "object",
        "properties": {
          "ts": {
            "type": "string",
            "format": "date-time",
            "example": "2026-07-27T00:00:00.000Z"
          },
          "count": {
            "type": "integer",
            "example": 599161
          }
        },
        "required": ["ts", "count"],
        "additionalProperties": false
      },

      "UsageData": {
        "type": "object",
        "properties": {
          "total_month": { "type": "integer", "example": 106087916 },
          "total_today": { "type": "integer", "example": 599161 },
          "breakdown": {
            "type": "array",
            "items": { "$ref": "#/components/schemas/UsageBreakdownItem" }
          }
        },
        "required": ["total_month", "total_today", "breakdown"],
        "additionalProperties": false
      },

      "UsageRequestResponse": {
        "type": "object",
        "properties": {
          "domain_url": { "type": "string", "example": "https://metrics.wepink.com.br" },
          "tagmanager_token": {
            "type": "string",
            "example": "GTM-XXXXXXX"
          },
          "granularity": {
            "type": "string",
            "enum": ["minute", "hour", "day", "month"],
            "example": "day"
          },
          "usage": { "$ref": "#/components/schemas/UsageData" }
        },
        "required": ["domain_url", "tagmanager_token", "granularity", "usage"],
        "additionalProperties": false
      },

      "WhatsAppClickInsert": {
        "type": "object",
        "properties": {
          "container_id": { "type": "integer", "example": 123 },
          "phone_e164": { "type": "string", "example": "+5511999999999" },
          "ga_client_id": { "type": "string", "example": "1234567890.1712345678" },
          "ga_session_id": { "type": "string", "example": "1712345678" },

          "gclid": { "type": "string", "nullable": true, "example": "Cj0KCQiA..." },
          "fbp": { "type": "string", "nullable": true, "example": "fb.1.1712345678901.1234567890" },
          "fbc": { "type": "string", "nullable": true, "example": "fb.1.1712345678901.AbCdEf..." },
          "ttclid": { "type": "string", "nullable": true, "example": "Ck0KC..." },
          "ttp": { "type": "string", "nullable": true, "example": "tiktok_cookie_value" },
          "epik": { "type": "string", "nullable": true, "example": "epik_value" },
          "twclid": { "type": "string", "nullable": true, "example": "twclid_value" },

          "page_url": { "type": "string", "nullable": true, "example": "https://loja.com.br/produto-x" },
          "utm_source": { "type": "string", "nullable": true, "example": "google" },
          "utm_medium": { "type": "string", "nullable": true, "example": "cpc" },
          "utm_campaign": { "type": "string", "nullable": true, "example": "campanha_wpp" },
          "utm_term": { "type": "string", "nullable": true, "example": "tenis masculino" },
          "utm_content": { "type": "string", "nullable": true, "example": "criativo_a" },

          "ip": {
            "type": "string",
            "nullable": true,
            "example": "203.0.113.10",
            "description": "IP (será castado para inet no SQL)"
          },
          "user_agent": {
            "type": "string",
            "nullable": true,
            "example": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ..."
          }
        },
        "required": ["container_id", "phone_e164", "ga_client_id", "ga_session_id"],
        "additionalProperties": false
      },

      "WhatsAppClickInsertResult": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "example": "9876543210" },
          "occurred_at": {
            "type": "string",
            "format": "date-time",
            "example": "2026-02-27T13:45:00.000Z"
          }
        },
        "required": ["id", "occurred_at"],
        "additionalProperties": false
      },

      "WhatsAppWebhook": {
        "type": "object",
        "properties": {
          "container_id": { "type": "integer", "example": 123 },
          "phone_e164": { "type": "string", "example": "+5511999999999" },
          "conversation_id": { "type": "string", "example": "conv_abc123" },
          "occurred_at": {
            "type": "string",
            "format": "date-time",
            "example": "2026-02-27T13:45:00.000Z"
          },
          "webhook_payload": {
            "nullable": true,
            "description": "Payload bruto recebido do provedor (estrutura livre).",
            "oneOf": [
              { "type": "object" },
              { "type": "array" },
              { "type": "string" },
              { "type": "number" },
              { "type": "boolean" },
              { "type": "null" }
            ],
            "example": { "event": "message", "data": { "text": "Oi" } }
          }
        },
        "required": ["container_id", "phone_e164", "conversation_id", "occurred_at"],
        "additionalProperties": false
      },

      "WhatsAppWebhookInsertResult": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "example": "1234567890" },
          "occurred_at": {
            "type": "string",
            "format": "date-time",
            "example": "2026-02-27T13:45:00.000Z"
          }
        },
        "required": ["id", "occurred_at"],
        "additionalProperties": false
      }
    }
  },

  "paths": {
    "/v1/usage/request": {
      "get": {
        "summary": "Consulta uso de requisições por granularidade",
        "description": "Retorna as métricas de uso para o domínio associado à API Key (total do mês, total de hoje e histórico por granularidade).",
        "security": [{ "TrastyApiKey": [] }],
        "parameters": [
          {
            "name": "granularity",
            "in": "query",
            "required": false,
            "description": "Granularidade do histórico (minute, hour, day, month). Padrão: hour",
            "schema": {
              "type": "string",
              "enum": ["minute", "hour", "day", "month"],
              "default": "hour"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Resposta com dados de uso",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/UsageRequestResponse" }
              }
            }
          },
          "400": {
            "description": "API Key ausente ou inválida",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": { "type": "string", "example": "Missing Api Key Storage." }
                  },
                  "required": ["error"],
                  "additionalProperties": false
                }
              }
            }
          },
          "403": {
            "description": "Não Autorizado",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": { "type": "string", "example": "Not Authorized." }
                  },
                  "required": ["error"],
                  "additionalProperties": false
                }
              }
            }
          }
        }
      }
    },

    "/v1/whatsapp/track/click": {
      "post": {
        "summary": "Track de clique do WhatsApp",
        "description": "Registra um clique/entrada via WhatsApp com identificadores de GA e atributos opcionais (gclid, fbp, utms, etc.).",
        "security": [{ "TrastyApiKey": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/WhatsAppClickInsert" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Registro inserido com sucesso",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/WhatsAppClickInsertResult" }
              }
            }
          },
          "400": {
            "description": "Payload inválido (validação do middleware)",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" }
              }
            }
          },
          "403": {
            "description": "Não autorizado (API Key inválida/sem permissão)",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" }
              }
            }
          },
          "500": {
            "description": "Erro interno",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" }
              }
            }
          }
        }
      }
    },

    "/v1/whatsapp/track/webhook": {
      "post": {
        "summary": "Track de webhook do WhatsApp",
        "description": "Registra um evento recebido via webhook (com conversation_id e occurred_at).",
        "security": [{ "TrastyApiKey": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/WhatsAppWebhook" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Registro inserido com sucesso",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/WhatsAppWebhookInsertResult" }
              }
            }
          },
          "400": {
            "description": "Payload inválido (validação do middleware)",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" }
              }
            }
          },
          "403": {
            "description": "Não autorizado (API Key inválida/sem permissão)",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" }
              }
            }
          },
          "500": {
            "description": "Erro interno",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ErrorResponse" }
              }
            }
          }
        }
      }
    }
  }
}