{
  "openapi": "3.1.0",
  "info": {
    "title": "NooriACS — Central de Integrações (painel)",
    "version": "1.0.0",
    "description": "Administração de conectores pelo painel do operador. Caminho de SESSÃO, não de integrador: a chave de integração (`/integrations/v1`) nunca autentica aqui, e o tenant vem sempre da sessão.\n\nDois tipos de conector na mesma lista:\n- `keys` (`INBOUND_KEY`): sistema externo chamando o NooriACS.\n- `erp` (`OUTBOUND_ERP`): o NooriACS chamando o ERP do provedor.\n\nPermissões: `integrations:read` para ver; `api:manage` para mexer em chave de entrada; `integrations:manage` para o conector de ERP. Testar exige a permissão de gerência do respectivo lado, porque dispara chamada de rede real."
  },
  "servers": [{ "url": "https://api.nooriacs.hosthub.net.br" }],
  "security": [{ "sessionCookie": [] }],
  "paths": {
    "/api/v1/integration-center": {
      "get": {
        "operationId": "listIntegrationCenter",
        "summary": "Lista unificada dos conectores da empresa",
        "responses": {
          "200": {
            "description": "Conectores, empresa, catálogo de escopos e a árvore de capacidades.",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CenterList" } } }
          },
          "403": { "$ref": "#/components/responses/Forbidden" }
        }
      }
    },
    "/api/v1/integration-center/{kind}/{id}/test": {
      "post": {
        "operationId": "testIntegration",
        "summary": "Verificação real do conector, em 7 passos",
        "description": "Executa a verificação na hora e guarda o resultado em `integration_health_checks`, que alimenta as colunas de última verificação e tempo de resposta da lista.\n\nPassos: conectividade, disponibilidade da API, credenciais, escopos, consulta real somente de leitura, tempo de resposta e compatibilidade das funcionalidades.\n\nNenhum passo altera equipamento nem envia evento de webhook: o retorno por webhook é conferido só por resolução de destino.",
        "parameters": [{ "$ref": "#/components/parameters/Kind" }, { "$ref": "#/components/parameters/Id" }],
        "responses": {
          "200": { "description": "Resultado da verificação.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HealthResult" } } } },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/v1/integration-center/{kind}/{id}/logs": {
      "get": {
        "operationId": "listIntegrationLogs",
        "summary": "Verificações e auditoria do conector",
        "parameters": [{ "$ref": "#/components/parameters/Kind" }, { "$ref": "#/components/parameters/Id" }],
        "responses": {
          "200": { "description": "Histórico em ordem decrescente de tempo.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Logs" } } } },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/v1/integration-center/{kind}/{id}/monitor": {
      "get": {
        "operationId": "getIntegrationMonitor",
        "summary": "Configuração e estado da vigilância automática",
        "parameters": [{ "$ref": "#/components/parameters/Kind" }, { "$ref": "#/components/parameters/Id" }],
        "responses": {
          "200": { "description": "Monitor atual, ou `null` quando o conector ainda não é vigiado.", "content": { "application/json": { "schema": { "type": "object", "properties": { "monitor": { "$ref": "#/components/schemas/Monitor" }, "intervals": { "type": "array", "items": { "enum": [1, 5, 10, 15, 30] } } } } } } },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      },
      "put": {
        "operationId": "setIntegrationMonitor",
        "summary": "Liga, desliga e ajusta a vigilância automática",
        "description": "A verificação roda no servidor, sem ninguém com o painel aberto, e usa exatamente a mesma rotina do teste manual.\n\nDesligar zera o incidente aberto: ninguém recebe “restabelecida” de algo que parou de ser vigiado.",
        "parameters": [{ "$ref": "#/components/parameters/Kind" }, { "$ref": "#/components/parameters/Id" }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MonitorInput" } } } },
        "responses": {
          "200": { "description": "Monitor gravado.", "content": { "application/json": { "schema": { "type": "object", "properties": { "monitor": { "$ref": "#/components/schemas/Monitor" } } } } } },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/v1/integration-center/{kind}/{id}/alerts": {
      "get": {
        "operationId": "listIntegrationAlerts",
        "summary": "Histórico de alertas do conector",
        "parameters": [{ "$ref": "#/components/parameters/Kind" }, { "$ref": "#/components/parameters/Id" }],
        "responses": {
          "200": { "description": "Alertas em ordem decrescente de tempo.", "content": { "application/json": { "schema": { "type": "object", "properties": { "items": { "type": "array", "items": { "$ref": "#/components/schemas/Alert" } } } } } } },
          "403": { "$ref": "#/components/responses/Forbidden" }
        }
      }
    },
    "/api/v1/integration-center/alert-settings": {
      "get": {
        "operationId": "getAlertSettings",
        "summary": "Canal de alerta da empresa, meus telefones e minhas preferências",
        "description": "O canal é da empresa e exige `integrations:manage` para alterar. Telefones e preferências são sempre do usuário autenticado: o `user_id` vem da sessão, nunca do corpo.",
        "responses": { "200": { "description": "Estado atual.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AlertSettings" } } } } }
      },
      "put": {
        "operationId": "setAlertSettings",
        "summary": "Grava canal, telefones e preferências",
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "type": "object", "additionalProperties": false, "properties": {
            "channel": { "$ref": "#/components/schemas/ChannelInput" },
            "phones": { "type": "array", "maxItems": 5, "items": { "type": "object", "required": ["phone"], "properties": { "phone": { "type": "string", "description": "DDI e DDD, só dígitos ou com máscara — o servidor normaliza." }, "label": { "type": ["string", "null"], "maxLength": 40 } } } },
            "preferences": { "type": "object", "properties": { "alerts": { "type": "object", "additionalProperties": { "type": "boolean" } } } }
          } } } }
        },
        "responses": {
          "200": { "description": "Gravado.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AlertSettings" } } } },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "409": { "description": "A configuração do canal mudou em outra aba." },
          "422": { "description": "Endereço, chave ou telefone inválido." }
        }
      }
    },
    "/api/v1/integration-center/alert-settings/test": {
      "post": {
        "operationId": "testAlertChannel",
        "summary": "Envia uma mensagem de teste pelo canal",
        "description": "Vai somente para o número de teste cadastrado na configuração, nunca para o telefone de um administrador: teste não é alerta.",
        "responses": {
          "200": { "description": "O HubOS aceitou a mensagem.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SendOutcome" } } } },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "409": { "description": "Canal não configurado, ou sem número de teste." },
          "502": { "description": "O HubOS recusou ou não respondeu.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SendOutcome" } } } }
        }
      }
    },
    "/api/v1/integration-center/keys/{id}": {
      "patch": {
        "operationId": "updateIntegrationKey",
        "summary": "Altera nome, funções, validade, origens liberadas e ativação",
        "description": "Campo ausente não é alterado. `expiresInDays: null` passa a validade indeterminada. `allowedCidrs: null` ou lista vazia volta a liberar qualquer origem. Chave revogada não é alterável: revogação é definitiva.",
        "parameters": [{ "$ref": "#/components/parameters/Id" }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/KeyPatch" } } } },
        "responses": {
          "200": { "description": "Chave alterada.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/KeyView" } } } },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "description": "Chave ativa não encontrada nesta empresa, ou a chave está revogada." }
        }
      },
      "delete": {
        "operationId": "deleteIntegrationKey",
        "summary": "Exclui a chave definitivamente",
        "description": "Apaga a chave e, em cascata, as assinaturas de webhook dela. Exige confirmação digitada com o nome exato do sistema. Para interromper o acesso preservando o registro, use a revogação em `/api/v1/integration-keys/{id}/revoke`.",
        "parameters": [{ "$ref": "#/components/parameters/Id" }],
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "type": "object", "required": ["confirm"], "properties": { "confirm": { "type": "string", "description": "Nome exato do sistema, como está cadastrado." } } } } }
        },
        "responses": {
          "200": { "description": "Excluída.", "content": { "application/json": { "schema": { "type": "object", "properties": { "deleted": { "const": true }, "id": { "type": "string", "format": "uuid" }, "webhooksRemoved": { "type": "integer" } } } } } },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "Confirmação ausente ou diferente do nome cadastrado." }
        }
      }
    },
    "/api/v1/integration-center/keys/{id}/duplicate": {
      "post": {
        "operationId": "duplicateIntegrationKey",
        "summary": "Duplica a chave com um segredo novo",
        "description": "A cópia nasce com as mesmas funções, validade e origens liberadas, e um segredo novo — o segredo original não existe em lugar nenhum, só o hash. O segredo da cópia é devolvido uma única vez.",
        "parameters": [{ "$ref": "#/components/parameters/Id" }],
        "requestBody": {
          "required": false,
          "content": { "application/json": { "schema": { "type": "object", "properties": { "integrator": { "type": "string", "pattern": "^[A-Za-z0-9 ._-]{2,64}$", "description": "Nome da cópia. Omitido, recebe um nome derivado do original." } } } } }
        },
        "responses": {
          "201": { "description": "Cópia criada.", "content": { "application/json": { "schema": { "allOf": [{ "$ref": "#/components/schemas/KeyView" }, { "type": "object", "properties": { "secret": { "type": "string" }, "secretShownOnce": { "const": true } } }] } } } },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "sessionCookie": { "type": "apiKey", "in": "cookie", "name": "nooriacs_session", "description": "Sessão do painel. Mutação exige mesma origem do APP_ORIGIN." }
    },
    "parameters": {
      "Kind": { "name": "kind", "in": "path", "required": true, "schema": { "enum": ["keys", "erp"] }, "description": "`keys` para chave de entrada, `erp` para conector de saída." },
      "Id": { "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } }
    },
    "responses": {
      "BadRequest": { "description": "Dado inválido.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "Forbidden": { "description": "O perfil não tem a permissão exigida.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "NotFound": { "description": "Conector não encontrado nesta empresa.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
    },
    "schemas": {
      "Error": { "type": "object", "required": ["error"], "properties": { "error": { "type": "string" }, "message": { "type": "string" }, "requestId": { "type": "string" } } },
      "CenterList": {
        "type": "object",
        "required": ["items", "availableScopes", "capabilities", "apiBaseUrl"],
        "properties": {
          "items": { "type": "array", "items": { "$ref": "#/components/schemas/CenterItem" } },
          "tenant": { "type": ["object", "null"], "properties": { "id": { "type": "string", "format": "uuid" }, "name": { "type": "string" }, "slug": { "type": "string" } } },
          "availableScopes": { "type": "array", "items": { "type": "string" } },
          "capabilities": { "type": "array", "items": { "$ref": "#/components/schemas/Capability" } },
          "apiBaseUrl": { "type": "string", "format": "uri", "description": "Endereço que o sistema integrador configura do lado dele. Não é segredo." },
          "docsUrl": { "type": "string", "format": "uri" },
          "slowResponseMs": { "type": "integer", "description": "Acima disso a integração é considerada lenta, não quebrada." }
        }
      },
      "CenterItem": {
        "type": "object",
        "required": ["kind", "id", "name", "direction", "state", "enabled", "lastCheck"],
        "properties": {
          "kind": { "enum": ["INBOUND_KEY", "OUTBOUND_ERP"] },
          "id": { "type": "string", "format": "uuid" },
          "name": { "type": "string" },
          "direction": { "enum": ["INBOUND", "OUTBOUND"] },
          "provider": { "type": ["string", "null"] },
          "state": { "enum": ["ACTIVE", "DISABLED", "REVOKED", "EXPIRED", "NOT_CONFIGURED", "CONNECTED", "ERROR"] },
          "enabled": { "type": "boolean" },
          "keyPrefix": { "type": "string", "description": "Início da chave. Serve para identificar a credencial em uso; não autentica." },
          "scopes": { "type": "array", "items": { "type": "string" } },
          "allowedCidrs": { "type": ["array", "null"], "items": { "type": "string" }, "description": "Nulo é qualquer origem. Preenchido, só estes IPs e redes autenticam." },
          "webhooks": { "type": "integer" },
          "expiresAt": { "type": ["string", "null"], "format": "date-time" },
          "lastUsedAt": { "type": ["string", "null"], "format": "date-time" },
          "rotatedAt": { "type": ["string", "null"], "format": "date-time" },
          "revision": { "type": "integer" },
          "configured": { "type": "boolean" },
          "lastSyncedAt": { "type": ["string", "null"], "format": "date-time" },
          "lastErrorCode": { "type": ["string", "null"] },
          "createdAt": { "type": ["string", "null"], "format": "date-time" },
          "lastCheck": {
            "type": ["object", "null"],
            "description": "Nulo é não testada. O estado nunca é inventado a partir de a URL responder.",
            "properties": { "status": { "enum": ["OPERATIONAL", "DEGRADED", "DOWN"] }, "at": { "type": "string", "format": "date-time" }, "durationMs": { "type": "integer" } }
          }
        }
      },
      "Capability": {
        "type": "object",
        "required": ["key", "group", "label", "scope", "mutating"],
        "description": "Folha da árvore de permissões, amarrada ao escopo que a rota exige no backend.",
        "properties": {
          "key": { "type": "string" },
          "group": { "type": "string" },
          "label": { "type": "string" },
          "scope": { "type": "string" },
          "mutating": { "type": "boolean", "description": "Verdadeiro quando a função altera o equipamento do cliente." }
        }
      },
      "HealthResult": {
        "type": "object",
        "required": ["status", "durationMs", "steps"],
        "properties": {
          "status": { "enum": ["OPERATIONAL", "DEGRADED", "DOWN"], "description": "FAIL em qualquer passo derruba; WARN ou SKIP viram operacional com limitações." },
          "durationMs": { "type": "integer" },
          "steps": { "type": "array", "items": { "$ref": "#/components/schemas/HealthStep" } }
        }
      },
      "HealthStep": {
        "type": "object",
        "required": ["key", "label", "status", "detail", "durationMs"],
        "properties": {
          "key": { "enum": ["endpoint", "api", "auth", "scopes", "read", "latency", "capabilities"] },
          "label": { "type": "string" },
          "status": { "enum": ["PASS", "WARN", "FAIL", "SKIP"] },
          "detail": { "type": "string", "description": "Frase para o operador. Nunca traz pilha, código cru nem segredo." },
          "durationMs": { "type": "integer" }
        }
      },
      "Logs": {
        "type": "object",
        "required": ["checks", "audit"],
        "properties": {
          "checks": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string", "format": "uuid" }, "status": { "enum": ["OPERATIONAL", "DEGRADED", "DOWN"] }, "durationMs": { "type": "integer" }, "steps": { "type": "array", "items": { "$ref": "#/components/schemas/HealthStep" } }, "origin": { "enum": ["MANUAL", "MONITOR"] }, "createdAt": { "type": "string", "format": "date-time" } } } },
          "audit": { "type": "array", "items": { "type": "object", "properties": { "action": { "type": "string" }, "outcome": { "type": "string" }, "metadata": { "type": "object" }, "createdAt": { "type": "string", "format": "date-time" }, "requestId": { "type": ["string", "null"] } } } }
        }
      },
      "MonitorInput": {
        "type": "object",
        "additionalProperties": false,
        "required": ["enabled", "intervalMinutes", "failureThreshold", "maxResponseMs"],
        "properties": {
          "enabled": { "type": "boolean" },
          "intervalMinutes": { "enum": [1, 5, 10, 15, 30], "description": "Valor livre não é aceito: verificação de segundo em segundo contra o ERP de um cliente é abuso disfarçado de monitoramento." },
          "failureThreshold": { "type": "integer", "minimum": 1, "maximum": 10, "description": "Falhas seguidas antes de abrir o incidente. É o que separa oscilação de queda." },
          "maxResponseMs": { "type": "integer", "minimum": 200, "maximum": 120000, "description": "Acima disso a verificação conta como falha, mesmo devolvendo 200." }
        }
      },
      "Monitor": {
        "type": ["object", "null"],
        "properties": {
          "enabled": { "type": "boolean" },
          "intervalMinutes": { "type": "integer" },
          "failureThreshold": { "type": "integer" },
          "maxResponseMs": { "type": "integer" },
          "consecutiveFailures": { "type": "integer" },
          "alertState": { "enum": ["OK", "ALERTING"] },
          "lastRunAt": { "type": ["string", "null"], "format": "date-time" },
          "lastStatus": { "type": ["string", "null"] },
          "nextRunAt": { "type": "string", "format": "date-time" },
          "incidentStartedAt": { "type": ["string", "null"], "format": "date-time" }
        }
      },
      "Alert": {
        "type": "object",
        "properties": {
          "alertType": { "enum": ["INTEGRATION_DOWN", "AUTH_FAILURE", "SLOW_API", "REPEATED_FAILURES", "RECOVERED"] },
          "phase": { "enum": ["OPENED", "RECOVERED"] },
          "status": { "enum": ["PENDING", "SENDING", "SENT", "FAILED", "UNKNOWN"], "description": "UNKNOWN é entrega de resultado ambíguo e NÃO é reenviada: repetir alerta de madrugada é tão ruim quanto não avisar." },
          "channel": { "type": ["string", "null"], "enum": ["WHATSAPP", "EMAIL", null] },
          "recipients": { "type": "integer" },
          "failureCode": { "type": ["string", "null"] },
          "createdAt": { "type": "string", "format": "date-time" },
          "sentAt": { "type": ["string", "null"], "format": "date-time" }
        }
      },
      "ChannelInput": {
        "type": "object",
        "additionalProperties": false,
        "required": ["enabled", "revision"],
        "description": "O NooriACS chama o HubOS, nunca a Evolution. Contrato: `POST {baseUrl}/api/public/whatsapp/send/{token}`.",
        "properties": {
          "enabled": { "type": "boolean" },
          "revision": { "type": "integer", "description": "Revisão otimista: o servidor recusa com 409 se a configuração mudou em outra aba." },
          "baseUrl": { "type": "string", "format": "uri", "description": "Origem do HubOS, HTTPS, sem usuário, senha, consulta ou âncora." },
          "token": { "type": "string", "description": "Chave de envio do HubOS. Vazio mantém a atual — ela nunca volta numa leitura." },
          "instanceId": { "type": "string" },
          "testNumber": { "type": "string" }
        }
      },
      "AlertSettings": {
        "type": "object",
        "properties": {
          "channel": {
            "type": "object",
            "description": "O token nunca aparece aqui, só `tokenPreview`.",
            "properties": {
              "configured": { "type": "boolean" }, "enabled": { "type": "boolean" }, "revision": { "type": "integer" },
              "baseUrl": { "type": "string" }, "instanceId": { "type": "string" }, "testNumber": { "type": "string" },
              "tokenPreview": { "type": "string" }, "lastTestedAt": { "type": ["string", "null"], "format": "date-time" },
              "lastErrorCode": { "type": ["string", "null"] }, "contrato": { "type": "string" }
            }
          },
          "phones": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string", "format": "uuid" }, "phone": { "type": "string" }, "label": { "type": ["string", "null"] } } } },
          "preferences": { "type": "object", "properties": { "alerts": { "type": "object", "additionalProperties": { "type": "boolean" } } } },
          "alertTypes": { "type": "array", "items": { "type": "object", "properties": { "type": { "type": "string" }, "label": { "type": "string" } } } },
          "maxPhones": { "type": "integer" },
          "canManageChannel": { "type": "boolean" }
        }
      },
      "SendOutcome": {
        "type": "object",
        "properties": {
          "status": { "enum": ["SENT", "FAILED", "PENDING", "UNKNOWN"] },
          "code": { "type": "string" }
        }
      },
      "KeyPatch": {
        "type": "object",
        "minProperties": 1,
        "additionalProperties": false,
        "properties": {
          "integrator": { "type": "string", "pattern": "^[A-Za-z0-9 ._-]{2,64}$" },
          "scopes": { "type": "array", "minItems": 1, "items": { "type": "string" } },
          "expiresInDays": { "type": ["integer", "null"], "minimum": 1, "maximum": 730, "description": "Nulo passa a validade indeterminada." },
          "allowedCidrs": {
            "type": ["array", "string", "null"],
            "description": "IPs e redes liberados, no máximo 20. Nulo, vazio ou lista vazia volta a liberar qualquer origem. Texto é aceito e separado por linha, vírgula ou ponto e vírgula.",
            "items": { "type": "string" }
          },
          "active": { "type": "boolean", "description": "Desativa ou reativa. Não serve para desfazer revogação." }
        }
      },
      "KeyView": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "integrator": { "type": "string" },
          "keyPrefix": { "type": "string" },
          "scopes": { "type": "array", "items": { "type": "string" } },
          "active": { "type": "boolean" },
          "createdAt": { "type": "string", "format": "date-time" },
          "expiresAt": { "type": ["string", "null"], "format": "date-time" },
          "lastUsedAt": { "type": ["string", "null"], "format": "date-time" },
          "rotatedAt": { "type": ["string", "null"], "format": "date-time" },
          "revokedAt": { "type": ["string", "null"], "format": "date-time" },
          "allowedCidrs": { "type": ["array", "null"], "items": { "type": "string" } }
        }
      }
    }
  }
}
