{
  "openapi": "3.1.0",
  "info": {
    "title": "Ruta API",
    "version": "1.0.0",
    "description": "API de Ruta (Quelion) para conectar un TMS u otro sistema. Fase 1: lectura de órdenes, su historial de etapas y el resumen de la operación. La escritura (alta de órdenes, cancelación, cambios) llega en la fase 2.",
    "contact": { "name": "Ruta, de Quelion", "url": "https://quelion.ai", "email": "hola@quelion.ai" }
  },
  "servers": [{ "url": "https://ruta.quelion.ai/api/v1" }],
  "security": [{ "bearer": [] }],
  "components": {
    "securitySchemes": {
      "bearer": { "type": "http", "scheme": "bearer", "description": "Clave de la cuenta, creada en el panel → Desarrolladores. Formato ruta_live_<prefijo>_<secreto>. Nunca en la URL." }
    },
    "parameters": {
      "ref": { "name": "ref", "in": "path", "required": true, "description": "Referencia de la orden, codificada para URL: 7964/8698 → 7964%2F8698.", "schema": { "type": "string", "maxLength": 120 } }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "required": ["error"],
        "properties": { "error": { "type": "object", "required": ["code", "message"], "properties": { "code": { "type": "string" }, "message": { "type": "string" } } } }
      },
      "Stop": {
        "type": "object",
        "properties": {
          "seq": { "type": ["integer", "null"] },
          "kind": { "type": "string", "enum": ["pickup", "delivery"] },
          "place": { "type": ["string", "null"] },
          "at": { "type": ["string", "null"], "format": "date-time", "description": "Cita en UTC." },
          "timezone": { "type": ["string", "null"], "description": "Zona IANA de la parada, p. ej. Europe/Lisbon." }
        }
      },
      "Order": {
        "type": "object",
        "required": ["ref", "status", "stage", "alert", "created_at"],
        "properties": {
          "ref": { "type": "string" },
          "client_ref": { "type": ["string", "null"] },
          "customer": { "type": ["string", "null"] },
          "origin": { "type": ["string", "null"] },
          "destination": { "type": ["string", "null"] },
          "operation_type": { "type": ["string", "null"], "description": "DOM-EU, DOM-MX, IMP-MX, EXP-MX, AIR, SEA." },
          "status": { "type": "string", "enum": ["active", "paused", "pending_review", "closed", "cancelled"] },
          "stage": { "type": ["string", "null"], "description": "Etapa: cargo_ready, in_transit, at_plant, delivered…" },
          "stage_updated_at": { "type": ["string", "null"], "format": "date-time" },
          "alert": { "type": "string", "enum": ["ok", "warning", "critical", "no_response"] },
          "paused_until": { "type": ["string", "null"], "format": "date-time" },
          "eta": { "type": ["string", "null"], "format": "date-time" },
          "appointments": {
            "type": "object",
            "properties": {
              "pickup_at": { "type": ["string", "null"], "format": "date-time" },
              "delivery_at": { "type": ["string", "null"], "format": "date-time" }
            }
          },
          "stops": { "type": "array", "items": { "$ref": "#/components/schemas/Stop" } },
          "contact_phone": { "type": ["string", "null"], "description": "Teléfono de seguimiento (conductor o tráfico del transportista), enmascarado: +34•••••0000." },
          "last_location": { "type": ["object", "null"], "properties": { "text": { "type": "string" }, "updated_at": { "type": ["string", "null"], "format": "date-time" } } },
          "intake_source": { "type": ["string", "null"], "description": "Cómo entró: panel, csv, email, mcp…" },
          "created_at": { "type": "string", "format": "date-time" },
          "updated_at": { "type": ["string", "null"], "format": "date-time", "description": "Último cambio con hora: etapa, ubicación, seguimiento o escalada, llegada a una parada." }
        }
      },
      "Event": {
        "type": "object",
        "properties": {
          "at": { "type": "string", "format": "date-time" },
          "from_stage": { "type": ["string", "null"] },
          "to_stage": { "type": ["string", "null"] }
        }
      }
    },
    "responses": {
      "Unauthorized": { "description": "Falta la clave, no es válida o fue revocada.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "Forbidden": { "description": "La clave no tiene el permiso o la cuenta no está activa.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "NotFound": { "description": "No existe la orden.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "RateLimited": { "description": "Más de 120 peticiones por minuto por cuenta.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
    }
  },
  "paths": {
    "/orders": {
      "get": {
        "operationId": "listOrders",
        "summary": "Listar órdenes",
        "parameters": [
          { "name": "status", "in": "query", "description": "active: en curso (incluye pausadas; no las altas pendientes de revisar). closed: entregadas y canceladas. Para sincronizar con updated_since use all.", "schema": { "type": "string", "enum": ["active", "closed", "all"], "default": "active" } },
          { "name": "updated_since", "in": "query", "description": "Solo órdenes con updated_at desde esta fecha (ISO 8601). Algunos cambios de alerta no cambian updated_at: para la alerta, recorra las activas.", "schema": { "type": "string", "format": "date-time" } },
          { "name": "limit", "in": "query", "schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 50 } },
          { "name": "cursor", "in": "query", "description": "next_cursor de la página anterior. Lleva los filtros de la primera página (status, updated_since).", "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "Una página de órdenes, de la más reciente a la más antigua.", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Order" } }, "next_cursor": { "type": ["string", "null"] } } } } } },
          "400": { "description": "Parámetro no válido.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/orders/{ref}": {
      "get": {
        "operationId": "getOrder",
        "summary": "Ver una orden",
        "parameters": [{ "$ref": "#/components/parameters/ref" }],
        "responses": {
          "200": { "description": "La orden.", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/Order" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/orders/{ref}/events": {
      "get": {
        "operationId": "getOrderEvents",
        "summary": "Historial de etapas de una orden",
        "parameters": [{ "$ref": "#/components/parameters/ref" }],
        "responses": {
          "200": { "description": "Cambios de etapa, del más antiguo al más reciente.", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Event" } } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/summary": {
      "get": {
        "operationId": "getSummary",
        "summary": "Resumen de la operación",
        "responses": {
          "200": { "description": "Órdenes activas por estado de alerta.", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "object", "properties": { "active": { "type": "integer" }, "warning": { "type": "integer" }, "critical": { "type": "integer", "description": "Órdenes en critical o no_response." }, "paused": { "type": "integer", "description": "Pausadas, sin contar las pendientes de revisar." }, "pending_review": { "type": "integer" } } } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    }
  }
}
