{
  "openapi": "3.0.3",
  "info": {
    "title": "Orbitta API",
    "version": "1.0.0",
    "description": "API REST para integração com dados do Orbitta. Acesse métricas, conversas, leads, alertas e muito mais de forma programática.",
    "contact": {
      "name": "Suporte Orbitta",
      "email": "suporte@orbitta.app.br",
      "url": "https://orbitta.app.br"
    },
    "license": {
      "name": "Proprietária",
      "url": "https://orbitta.app.br/terms"
    }
  },
  "servers": [
    {
      "url": "https://api.orbitta.app.br/v1",
      "description": "Servidor de Produção"
    }
  ],
  "security": [
    {
      "bearerAuth": []
    }
  ],
  "tags": [
    { "name": "Lojas", "description": "Gerenciamento e consulta de lojas" },
    { "name": "Métricas", "description": "Métricas de desempenho e KPIs" },
    { "name": "Conversas", "description": "Histórico de conversas do WhatsApp" },
    { "name": "Leads", "description": "Gerenciamento de leads/clientes" },
    { "name": "Agendamentos", "description": "Detecção automática de agendamentos" },
    { "name": "Alertas", "description": "Sistema de alertas e notificações" },
    { "name": "Intelligence", "description": "Inteligência comercial e insights" }
  ],
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "API Key",
        "description": "Use sua chave de API no formato: Bearer wmk_live_sua_chave"
      }
    },
    "schemas": {
      "Store": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid", "description": "ID único da loja" },
          "name": { "type": "string", "description": "Nome da loja" },
          "group_id": { "type": "string", "format": "uuid", "description": "ID do grupo" },
          "group_name": { "type": "string", "description": "Nome do grupo" },
          "phone_number": { "type": "string", "nullable": true, "description": "Número do WhatsApp" },
          "status": { "type": "string", "enum": ["online", "offline", "connecting"], "description": "Status da loja" },
          "connection_status": { "type": "string", "description": "Status de conexão WhatsApp" },
          "address": { "type": "string", "nullable": true, "description": "Endereço da loja" },
          "manager": { "type": "string", "nullable": true, "description": "Nome do gerente" },
          "score": { "type": "integer", "minimum": 0, "maximum": 100, "description": "Score de desempenho" },
          "created_at": { "type": "string", "format": "date-time", "description": "Data de criação" }
        }
      },
      "MetricDaily": {
        "type": "object",
        "properties": {
          "date": { "type": "string", "format": "date", "description": "Data da métrica" },
          "entries_count": { "type": "integer", "description": "Novos atendimentos iniciados" },
          "conversations_started": { "type": "integer", "description": "Conversas iniciadas pela loja" },
          "bookings_count": { "type": "integer", "description": "Agendamentos detectados" },
          "tmr_minutes": { "type": "number", "description": "Tempo médio de resposta em minutos" },
          "coverage_hours": { "type": "number", "description": "Cobertura de atendimento em horas" },
          "abandonment_rate": { "type": "number", "description": "Taxa de abandono (%)" },
          "reopening_7days": { "type": "number", "description": "Taxa de reabertura em 7 dias (%)" },
          "sentiment_score": { "type": "number", "description": "Score de sentimento médio" }
        }
      },
      "MetricsSummary": {
        "type": "object",
        "properties": {
          "total_entries": { "type": "integer", "description": "Total de atendimentos" },
          "total_conversations": { "type": "integer", "description": "Total de conversas" },
          "total_bookings": { "type": "integer", "description": "Total de agendamentos" },
          "avg_tmr_minutes": { "type": "number", "description": "TMR médio em minutos" },
          "avg_coverage_percent": { "type": "number", "description": "Cobertura média (%)" },
          "avg_abandonment_percent": { "type": "number", "description": "Abandono médio (%)" }
        }
      },
      "Conversation": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "store_id": { "type": "string", "format": "uuid" },
          "store_name": { "type": "string" },
          "contact_name": { "type": "string", "nullable": true },
          "phone_number": { "type": "string" },
          "last_message_at": { "type": "string", "format": "date-time", "nullable": true },
          "unread_count": { "type": "integer" },
          "ai_summary": { "type": "string", "nullable": true, "description": "Resumo gerado por IA" },
          "created_at": { "type": "string", "format": "date-time" }
        }
      },
      "Lead": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "phone_number": { "type": "string" },
          "name": { "type": "string", "nullable": true },
          "store_id": { "type": "string", "format": "uuid" },
          "store_name": { "type": "string" },
          "first_contact_at": { "type": "string", "format": "date-time", "nullable": true },
          "last_contact_at": { "type": "string", "format": "date-time", "nullable": true },
          "total_conversations": { "type": "integer" },
          "total_messages": { "type": "integer" },
          "average_sentiment": { "type": "number", "nullable": true },
          "tags": { "type": "array", "items": { "type": "string" }, "nullable": true },
          "notes": { "type": "string", "nullable": true }
        }
      },
      "LeadUpdate": {
        "type": "object",
        "properties": {
          "name": { "type": "string", "description": "Nome do lead" },
          "tags": { "type": "array", "items": { "type": "string" }, "description": "Tags do lead" },
          "notes": { "type": "string", "description": "Notas sobre o lead" }
        }
      },
      "Booking": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "store_id": { "type": "string", "format": "uuid" },
          "store_name": { "type": "string" },
          "customer_phone": { "type": "string", "nullable": true },
          "customer_name": { "type": "string", "nullable": true },
          "booking_date": { "type": "string", "format": "date", "nullable": true },
          "booking_time": { "type": "string", "nullable": true },
          "detected_at": { "type": "string", "format": "date-time" },
          "detection_method": { "type": "string", "enum": ["pattern", "ai"], "description": "Método de detecção" },
          "confidence_score": { "type": "number", "nullable": true, "description": "Confiança da detecção (0-1)" }
        }
      },
      "Alert": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "store_id": { "type": "string", "format": "uuid" },
          "store_name": { "type": "string" },
          "type": { "type": "string", "enum": ["disconnection", "low_response", "high_abandonment", "sentiment_drop"], "description": "Tipo do alerta" },
          "severity": { "type": "string", "enum": ["info", "warning", "critical"], "description": "Severidade" },
          "message": { "type": "string", "description": "Mensagem do alerta" },
          "acknowledged": { "type": "boolean", "description": "Se foi reconhecido" },
          "metadata": { "type": "object", "nullable": true },
          "created_at": { "type": "string", "format": "date-time" }
        }
      },
      "IntelligenceSummary": {
        "type": "object",
        "properties": {
          "executive_summary": { "type": "string", "description": "Resumo executivo gerado por IA" },
          "key_insights": { "type": "array", "items": { "type": "string" } },
          "opportunities": { "type": "array", "items": { "type": "string" } },
          "risks": { "type": "array", "items": { "type": "string" } },
          "recommendations": { "type": "array", "items": { "type": "string" } },
          "period": { "type": "object", "properties": { "start_date": { "type": "string" }, "end_date": { "type": "string" } } },
          "stores_analyzed": { "type": "integer" },
          "conversations_analyzed": { "type": "integer" }
        }
      },
      "PaginationMeta": {
        "type": "object",
        "properties": {
          "total": { "type": "integer", "description": "Total de registros" },
          "page": { "type": "integer", "description": "Página atual" },
          "per_page": { "type": "integer", "description": "Itens por página" },
          "total_pages": { "type": "integer", "description": "Total de páginas" }
        }
      },
      "PaginationLinks": {
        "type": "object",
        "properties": {
          "self": { "type": "string" },
          "prev": { "type": "string" },
          "next": { "type": "string" },
          "last": { "type": "string" }
        }
      },
      "Error": {
        "type": "object",
        "properties": {
          "error": {
            "type": "object",
            "properties": {
              "code": { "type": "string", "description": "Código do erro" },
              "message": { "type": "string", "description": "Mensagem descritiva" }
            }
          },
          "request_id": { "type": "string", "format": "uuid", "description": "ID da requisição para suporte" }
        }
      }
    },
    "parameters": {
      "page": {
        "name": "page",
        "in": "query",
        "description": "Número da página",
        "schema": { "type": "integer", "default": 1, "minimum": 1 }
      },
      "per_page": {
        "name": "per_page",
        "in": "query",
        "description": "Itens por página (máx 100)",
        "schema": { "type": "integer", "default": 20, "minimum": 1, "maximum": 100 }
      },
      "start_date": {
        "name": "start_date",
        "in": "query",
        "description": "Data inicial (YYYY-MM-DD)",
        "schema": { "type": "string", "format": "date" }
      },
      "end_date": {
        "name": "end_date",
        "in": "query",
        "description": "Data final (YYYY-MM-DD)",
        "schema": { "type": "string", "format": "date" }
      },
      "store_id": {
        "name": "store_id",
        "in": "query",
        "description": "Filtrar por loja",
        "schema": { "type": "string", "format": "uuid" }
      },
      "group_id": {
        "name": "group_id",
        "in": "query",
        "description": "Filtrar por grupo",
        "schema": { "type": "string", "format": "uuid" }
      }
    },
    "responses": {
      "Unauthorized": {
        "description": "Chave de API ausente ou inválida",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/Error" },
            "example": {
              "error": { "code": "UNAUTHORIZED", "message": "API key is required" },
              "request_id": "550e8400-e29b-41d4-a716-446655440000"
            }
          }
        }
      },
      "Forbidden": {
        "description": "Sem permissão para acessar este recurso",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/Error" }
          }
        }
      },
      "NotFound": {
        "description": "Recurso não encontrado",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/Error" }
          }
        }
      },
      "RateLimited": {
        "description": "Limite de requisições excedido",
        "headers": {
          "X-RateLimit-Limit": { "schema": { "type": "integer" }, "description": "Limite por minuto" },
          "X-RateLimit-Remaining": { "schema": { "type": "integer" }, "description": "Requisições restantes" },
          "X-RateLimit-Reset": { "schema": { "type": "integer" }, "description": "Segundos até reset" }
        },
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/Error" }
          }
        }
      }
    }
  },
  "paths": {
    "/stores": {
      "get": {
        "tags": ["Lojas"],
        "summary": "Listar lojas",
        "description": "Retorna uma lista paginada de todas as lojas do tenant",
        "operationId": "listStores",
        "parameters": [
          { "$ref": "#/components/parameters/page" },
          { "$ref": "#/components/parameters/per_page" },
          { "$ref": "#/components/parameters/group_id" },
          {
            "name": "status",
            "in": "query",
            "description": "Filtrar por status",
            "schema": { "type": "string", "enum": ["online", "offline", "connecting"] }
          }
        ],
        "responses": {
          "200": {
            "description": "Lista de lojas",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": { "type": "array", "items": { "$ref": "#/components/schemas/Store" } },
                    "meta": { "$ref": "#/components/schemas/PaginationMeta" },
                    "links": { "$ref": "#/components/schemas/PaginationLinks" }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/stores/{id}": {
      "get": {
        "tags": ["Lojas"],
        "summary": "Obter detalhes de uma loja",
        "operationId": "getStore",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "ID da loja",
            "schema": { "type": "string", "format": "uuid" }
          }
        ],
        "responses": {
          "200": {
            "description": "Detalhes da loja",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": {
                      "type": "object",
                      "properties": {
                        "id": { "type": "string" },
                        "type": { "type": "string", "example": "store" },
                        "attributes": { "$ref": "#/components/schemas/Store" }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/stores/{id}/metrics": {
      "get": {
        "tags": ["Métricas"],
        "summary": "Métricas de uma loja",
        "description": "Retorna métricas diárias de uma loja específica",
        "operationId": "getStoreMetrics",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string", "format": "uuid" }
          },
          { "$ref": "#/components/parameters/start_date" },
          { "$ref": "#/components/parameters/end_date" }
        ],
        "responses": {
          "200": {
            "description": "Métricas da loja",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": {
                      "type": "object",
                      "properties": {
                        "store_id": { "type": "string" },
                        "period": { "type": "object", "properties": { "start_date": { "type": "string" }, "end_date": { "type": "string" } } },
                        "summary": { "$ref": "#/components/schemas/MetricsSummary" },
                        "daily": { "type": "array", "items": { "$ref": "#/components/schemas/MetricDaily" } }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/metrics": {
      "get": {
        "tags": ["Métricas"],
        "summary": "Métricas agregadas",
        "description": "Retorna métricas agregadas de todas as lojas ou filtradas por grupo/loja",
        "operationId": "getAggregatedMetrics",
        "parameters": [
          { "$ref": "#/components/parameters/start_date" },
          { "$ref": "#/components/parameters/end_date" },
          { "$ref": "#/components/parameters/store_id" },
          { "$ref": "#/components/parameters/group_id" }
        ],
        "responses": {
          "200": {
            "description": "Métricas agregadas",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": {
                      "type": "object",
                      "properties": {
                        "period": { "type": "object" },
                        "stores_count": { "type": "integer" },
                        "metrics": { "$ref": "#/components/schemas/MetricsSummary" }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/metrics/daily": {
      "get": {
        "tags": ["Métricas"],
        "summary": "Métricas diárias",
        "description": "Retorna série temporal de métricas agrupadas por dia",
        "operationId": "getDailyMetrics",
        "parameters": [
          { "$ref": "#/components/parameters/start_date" },
          { "$ref": "#/components/parameters/end_date" },
          { "$ref": "#/components/parameters/store_id" }
        ],
        "responses": {
          "200": {
            "description": "Série temporal de métricas",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": { "type": "array", "items": { "$ref": "#/components/schemas/MetricDaily" } }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/conversations": {
      "get": {
        "tags": ["Conversas"],
        "summary": "Listar conversas",
        "description": "Retorna lista paginada de conversas do WhatsApp",
        "operationId": "listConversations",
        "parameters": [
          { "$ref": "#/components/parameters/page" },
          { "$ref": "#/components/parameters/per_page" },
          { "$ref": "#/components/parameters/store_id" }
        ],
        "responses": {
          "200": {
            "description": "Lista de conversas",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": { "type": "array", "items": { "$ref": "#/components/schemas/Conversation" } },
                    "meta": { "$ref": "#/components/schemas/PaginationMeta" },
                    "links": { "$ref": "#/components/schemas/PaginationLinks" }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/leads": {
      "get": {
        "tags": ["Leads"],
        "summary": "Listar leads",
        "description": "Retorna uma linha por cliente e Unidade. O mesmo cliente mantém o mesmo id em Unidades diferentes; a chave da linha é o par id e store_id. As datas first_contact_at, last_contact_at e created_at pertencem à Unidade da linha. meta.total conta essas linhas, não clientes distintos. Os demais dados continuam pertencendo à ficha do cliente. Detalhe e edição por id continuam identificando o cliente.",
        "operationId": "listLeads",
        "parameters": [
          { "$ref": "#/components/parameters/page" },
          { "$ref": "#/components/parameters/per_page" },
          { "$ref": "#/components/parameters/store_id" }
        ],
        "responses": {
          "200": {
            "description": "Lista de leads",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": { "type": "array", "items": { "$ref": "#/components/schemas/Lead" } },
                    "meta": { "$ref": "#/components/schemas/PaginationMeta" },
                    "links": { "$ref": "#/components/schemas/PaginationLinks" }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/leads/{id}": {
      "get": {
        "tags": ["Leads"],
        "summary": "Obter detalhes de um lead",
        "operationId": "getLead",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string", "format": "uuid" }
          }
        ],
        "responses": {
          "200": {
            "description": "Detalhes do lead",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": { "$ref": "#/components/schemas/Lead" }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      },
      "patch": {
        "tags": ["Leads"],
        "summary": "Atualizar um lead",
        "description": "Atualiza nome, tags ou notas de um lead",
        "operationId": "updateLead",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string", "format": "uuid" }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/LeadUpdate" },
              "example": {
                "name": "João Silva",
                "tags": ["vip", "recorrente"],
                "notes": "Cliente desde 2023, prefere agendamentos pela manhã"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Lead atualizado",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": { "$ref": "#/components/schemas/Lead" }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/bookings": {
      "get": {
        "tags": ["Agendamentos"],
        "summary": "Listar agendamentos",
        "description": "Retorna agendamentos detectados automaticamente nas conversas",
        "operationId": "listBookings",
        "parameters": [
          { "$ref": "#/components/parameters/page" },
          { "$ref": "#/components/parameters/per_page" },
          { "$ref": "#/components/parameters/store_id" },
          { "$ref": "#/components/parameters/start_date" },
          { "$ref": "#/components/parameters/end_date" }
        ],
        "responses": {
          "200": {
            "description": "Lista de agendamentos",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": { "type": "array", "items": { "$ref": "#/components/schemas/Booking" } },
                    "meta": { "$ref": "#/components/schemas/PaginationMeta" },
                    "links": { "$ref": "#/components/schemas/PaginationLinks" }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/alerts": {
      "get": {
        "tags": ["Alertas"],
        "summary": "Listar alertas",
        "description": "Retorna alertas do sistema para as lojas",
        "operationId": "listAlerts",
        "parameters": [
          { "$ref": "#/components/parameters/page" },
          { "$ref": "#/components/parameters/per_page" },
          { "$ref": "#/components/parameters/store_id" },
          {
            "name": "acknowledged",
            "in": "query",
            "description": "Filtrar por status de reconhecimento",
            "schema": { "type": "boolean" }
          }
        ],
        "responses": {
          "200": {
            "description": "Lista de alertas",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": { "type": "array", "items": { "$ref": "#/components/schemas/Alert" } },
                    "meta": { "$ref": "#/components/schemas/PaginationMeta" },
                    "links": { "$ref": "#/components/schemas/PaginationLinks" }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/alerts/{id}/acknowledge": {
      "post": {
        "tags": ["Alertas"],
        "summary": "Reconhecer um alerta",
        "description": "Marca um alerta como reconhecido",
        "operationId": "acknowledgeAlert",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string", "format": "uuid" }
          }
        ],
        "responses": {
          "200": {
            "description": "Alerta reconhecido",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": { "type": "boolean", "example": true },
                    "message": { "type": "string", "example": "Alerta reconhecido com sucesso" }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/intelligence/summary": {
      "get": {
        "tags": ["Intelligence"],
        "summary": "Resumo de inteligência comercial",
        "description": "Retorna análise de IA com insights, oportunidades e recomendações baseadas nas conversas",
        "operationId": "getIntelligenceSummary",
        "parameters": [
          {
            "name": "store_ids",
            "in": "query",
            "description": "IDs das lojas separados por vírgula (opcional)",
            "schema": { "type": "string" },
            "example": "uuid1,uuid2"
          }
        ],
        "responses": {
          "200": {
            "description": "Resumo de inteligência",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "data": { "$ref": "#/components/schemas/IntelligenceSummary" }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    }
  }
}
