openapi: 3.0.3
info:
  title: Envíala API
  version: "1.4"
  description: |
    API pública de envíala para envíos contra entrega (COD) y prepago en Colombia: cotizar, crear
    guías (una a una o en lote), etiqueta, rastreo, manifiestos, recogidas, novedades, score de
    destinatarios, lectura de la cuenta/wallet y webhooks firmados.

    **Fuente de verdad:** este archivo se valida en CI contra las rutas reales del backend
    (`src/__tests__/integration/api/openapi-coherence.test.ts`).

    ## Autenticación
    Todas las rutas (salvo el rastreo público por guía) requieren una API key en el header
    `X-API-Key`. Las keys se crean en el panel (**Ajustes → Desarrolladores**) con un **modo**
    (`LIVE` o `TEST`) y al menos un **scope**. El valor en claro se muestra una sola vez.
    Prefijos: `env_live_…` y `env_test_…`.

    ## Scopes
    `shipments:read`, `shipments:write`, `tracking:read`, `manifests:read`, `manifests:write`,
    `novelties:read`, `novelties:write`, `score:read`, `wallet:read`, `webhooks:manage`,
    `pickups:read`, `pickups:write`. Sin el scope requerido → `403 forbidden_scope`.
    No existe ningún scope para mover dinero: recargas y retiros solo desde el panel.

    ## Envelope
    - Éxito: `{ "success": true, "data": … }`
    - Error: `{ "success": false, "error": { "code", "message", "details"? } }`

    | HTTP | `code` | Cuándo |
    |---|---|---|
    | 400 | `invalid_body` | JSON malformado o body que no es un objeto |
    | 401 | `unauthorized` | Falta la API key, es inválida, está revocada o la cuenta no está activa |
    | 402 | `insufficient_balance` | Prepago sin saldo (`details: {available, required}`) |
    | 403 | `forbidden_scope` | La key no tiene el scope |
    | 403 | `test_mode_only` | Endpoint solo para keys TEST (`/envios/{id}/simular`) |
    | 404 | `not_found` | Recurso inexistente, de otro comercio o de otro modo (TEST/LIVE) |
    | 409 | `conflict` | El estado actual impide la acción (cancelar algo ya recogido, novedad ya resuelta, URL de webhook duplicada) |
    | 409 | `idempotency_key_reuse` | Misma `Idempotency-Key` con otro cuerpo |
    | 409 | `idempotency_in_progress` | Otra solicitud con la misma `Idempotency-Key` aún se procesa |
    | 422 | `validation_error` | Datos inválidos: `details.issues: [{path, message}]` con la ruta completa (`recipient.address`) |
    | 422 | `carrier_rejected` | La transportadora rechazó los datos (`details: {carrier, carrierCode, field?}`); no se arregla reintentando |
    | 429 | `rate_limited` | Más de 120 solicitudes por minuto por key o 300 por comercio (ver `Retry-After`) |
    | 429 | `sandbox_limit` | Key TEST: el comercio llegó al tope de 1.000 envíos de prueba vivos |
    | 500 | `internal_error` | Error interno (sin detalles) |
    | 502 | `carrier_unavailable` | La transportadora no respondió o falló (reintentable) |

    Si una creación falla después de crear el borrador, `details` trae `shipmentId` y `status`
    (`CANCELLED` si se anuló; `DRAFT` + `guideOutcome: "unknown"` si la transportadora no respondió
    y el resultado es incierto: el equipo de envíala lo concilia, no lo recrees con otra
    `Idempotency-Key`). Solo las transportadoras con creación idempotente (Envíala Express) se
    reintentan solas una vez tras un timeout. Cancelar por API un borrador así intenta anular la
    guía en la transportadora con la misma referencia.

    ## Idempotencia
    `POST /envios`, `POST /envios/bulk`, `POST /manifiestos` y `POST /recogidas` aceptan `Idempotency-Key`
    (máx. 255 caracteres). La clave se **reserva antes de ejecutar** y se separa por **endpoint**
    y por **modo** de la key (TEST/LIVE):
    - misma clave + mismo cuerpo (el orden de las propiedades no importa) → la respuesta original;
    - misma clave + otro cuerpo → `409 idempotency_key_reuse`;
    - misma clave mientras la primera aún se procesa → `409 idempotency_in_progress` (reintenta en
      unos segundos: recibirás la respuesta original);
    - se guardan las respuestas 2xx y 4xx (salvo 409/429) y el `502` con `guideOutcome: "unknown"`;
      cualquier otro 5xx libera la clave para reintentar.
    Si cortas la conexión por timeout, la solicitud sigue y su resultado queda guardado: reintenta
    con la **misma** clave.

    ## Rate limit
    120 solicitudes por minuto por API key y 300 por comercio (sumando todas sus keys). Cada
    respuesta autenticada trae `X-RateLimit-Limit`,
    `X-RateLimit-Remaining` y `X-RateLimit-Reset` (epoch en segundos); el `429` trae además
    `Retry-After` (segundos). El rastreo público tiene su propio tope por IP.

    ## Sandbox (keys TEST)
    Una key TEST trabaja **solo con datos de prueba** y nunca ve ni toca datos LIVE (ni al revés):
    - `POST /envios` y `/envios/bulk` crean envíos de prueba **persistidos** (`TEST-…`), con el mismo
      DTO, estado (`PENDING_PICKUP`), validaciones y cobertura que LIVE (Envíala Express solo Bogotá),
      sin llamar a ninguna transportadora ni tocar el wallet.
    - Detalle, listado, eventos, etiqueta, cancelar y rastreo público funcionan con esos envíos.
    - `POST /envios/{id}/simular` avanza el estado y dispara los webhooks a tus endpoints **TEST**.
    - `/cotizar` devuelve precios **simulados y deterministas** (`simulated: true`).
    - Manifiestos y recogidas se **simulan** (no se guardan): `GET` devuelve listas vacías.
    - Wallet (`/saldo`, `/movimientos`, `/cartera`) responde en cero con `isTest: true`.
    - Los webhooks registrados con una key TEST solo reciben eventos del sandbox (`mode: TEST`).
    - El lead de landing con key TEST se simula.
    - Tope: 1.000 envíos de prueba vivos por comercio (`429 sandbox_limit`); los envíos de prueba
      se borran solos a los 30 días.
    - Los envíos de prueba nunca cuentan para dinero ni métricas (puntos, referidos, adelantos,
      recogidas reales, estadísticas).

    ## Mismo día en Bogotá (ENVIALA_EXPRESS)
    Entrega el mismo día si se pide de **lunes a viernes antes de las 3:00 p. m.** o el **sábado
    antes de las 11:00 a. m.** (hora Bogotá); sin reparto domingos ni festivos (si no, el siguiente
    día de reparto). `/cotizar` trae `cutoff` y el envío trae `estimatedDelivery` (fin del día de
    reparto, hora Bogotá). Envía siempre `destinationAddress` al cotizar: la transportadora la exige.

    ## Webhooks
    Ver el tag **Webhooks** y el esquema `WebhookPayload`. Firma:
    `X-Enviala-Signature = hex(HMAC-SHA256(secret, timestamp + "." + rawBody))` con
    `timestamp = X-Enviala-Timestamp` (epoch en **milisegundos**).
servers:
  - url: https://api.enviala.co
    description: Producción (las keys TEST usan el mismo host)

tags:
  - name: Envíos
  - name: Cotización
  - name: Rastreo
  - name: Manifiestos
  - name: Recogidas
  - name: Novedades
  - name: Score
  - name: Cuenta
  - name: Webhooks
    description: |
      Cada entrega es un `POST` JSON a tu URL (https, IP pública) con los headers
      `X-Enviala-Event`, `X-Enviala-Timestamp` (epoch ms), `X-Enviala-Signature`,
      `X-Enviala-Event-Id` (igual para todas las entregas de un mismo evento: úsalo para
      deduplicar) y `X-Enviala-Delivery-Id` (id de esta entrega).

      Responde **2xx** en menos de 10 s. Si no: reintentos con esperas de 1, 5, 30, 120 y 360
      minutos (6 intentos en total) y luego `FAILED`; puedes reintentar a mano (reinicia los
      intentos). Los redirects (3xx) no se siguen y cuentan como fallo. Se guardan como máximo
      200 caracteres de tu respuesta.

      **Verificación (Node.js)** — sobre el cuerpo CRUDO, antes de parsear el JSON:
      ```js
      import crypto from 'node:crypto'

      const TOLERANCE_MS = 5 * 60 * 1000 // rechaza entregas de hace más de 5 minutos

      export function verifyEnvialaWebhook(rawBody, headers, secret) {
        const timestamp = headers['x-enviala-timestamp']
        const signature = headers['x-enviala-signature']
        if (!timestamp || !signature) return false
        if (Math.abs(Date.now() - Number(timestamp)) > TOLERANCE_MS) return false
        const expected = crypto
          .createHmac('sha256', secret)
          .update(`${timestamp}.${rawBody}`)
          .digest('hex')
        const a = Buffer.from(expected, 'hex')
        const b = Buffer.from(String(signature), 'hex')
        // timingSafeEqual lanza si los largos difieren: compáralos antes.
        return a.length === b.length && crypto.timingSafeEqual(a, b)
      }
      ```
      Con Express usa `express.raw({ type: 'application/json' })` en esa ruta para tener el
      cuerpo crudo.

      **Cuerpo de cada evento:** el esquema `WebhookPayload` trae un ejemplo JSON por evento
      (envío, novedad, reprogramado, recaudo liquidado y adelantos) y qué significa cada campo.
      Resumen:

      | Evento | Campos además de los del envío* |
      |---|---|
      | `envio.creado`, `envio.recogido`, `envio.en_camino`, `envio.entregado`, `envio.devuelto` | — |
      | `envio.novedad` | `noveltyId`, `shipmentId`, `type`, `note` |
      | `envio.reprogramado` | `novelty { id, type, action, note, resolvedAt, scheduledDate?, slot? }` |
      | `recaudo.liquidado` | `shipmentId`, `settlementId`, `delta`, `shipmentStatus` |
      | `adelanto.aprobado` | solo `advanceId`, `amount` (sin campos del envío) |
      | `adelanto.saldado` | solo `advanceId`, `amount`, `totalToRecover` (sin campos del envío) |

      \* Campos del envío: `id`, `trackingNumber`, `externalId`, `carrierSlug`, `status`, `livemode`.
      Todos los cuerpos traen además `event`, `eventId` y `occurredAt`.

security:
  - ApiKeyAuth: []

paths:
  # ─── Envíos ─────────────────────────────────────────────────────────────────
  /api/v1/envios:
    post:
      tags: [Envíos]
      summary: Crear envío y generar la guía
      description: |
        **Scope:** `shipments:write`. Idempotente con `Idempotency-Key`.
        LIVE: crea el pedido y genera la guía con la transportadora (prepago descuenta flete+prima
        del wallet; COD se liquida al entregar). Si la guía no sale, el borrador se anula y el error
        trae `details.shipmentId`/`status`. TEST: envío de prueba persistido (ver Sandbox).
        `carrierSlug` es obligatorio (no hay auto-selección): usa `/cotizar` antes.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateShipment' }
            example:
              carrierSlug: ENVIALA_EXPRESS
              shipmentType: COD
              codAmount: 85000
              insuranceTier: NONE
              recipient:
                name: Laura Gómez
                phone: "+57 300 123 4567"
                address: 'Carrera 15 # 93-47 Apto 501'
                city: Bogotá
                department: Bogotá D.C.
                email: laura@example.com
              product: { description: Tenis running talla 38, weight: 1, declaredValue: 85000 }
              deliveryNotes: Portería torre 2
              externalId: MARCA-100231
      responses:
        '201':
          description: Envío creado con guía
          headers: { $ref: '#/components/headers/RateLimitSet' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShipmentEnvelope' }
        '400': { $ref: '#/components/responses/InvalidBody' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '402': { $ref: '#/components/responses/InsufficientBalance' }
        '403': { $ref: '#/components/responses/ForbiddenScope' }
        '409': { $ref: '#/components/responses/IdempotencyConflict' }
        '422': { $ref: '#/components/responses/ValidationOrCarrierRejected' }
        '429': { $ref: '#/components/responses/RateLimitedOrSandboxLimit' }
        '500': { $ref: '#/components/responses/Internal' }
        '502': { $ref: '#/components/responses/CarrierUnavailable' }
    get:
      tags: [Envíos]
      summary: Listar envíos (cursor)
      description: |
        **Scope:** `shipments:read`. Solo los envíos del modo de la key. Sin filtros lista todos
        (incluidos los cancelados). `total` respeta los filtros. Orden: más reciente primero.
      parameters:
        - { name: cursor, in: query, schema: { type: string }, description: '`nextCursor` de la página anterior (otro valor → 422).' }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
        - { name: status, in: query, schema: { $ref: '#/components/schemas/ShipmentStatus' }, description: Acepta minúsculas. }
        - { name: group, in: query, schema: { type: string, enum: [created, pickup, distribution, delivered, prepaid] } }
        - { name: externalId, in: query, schema: { type: string }, description: Tu número de pedido. }
        - { name: guia, in: query, schema: { type: string }, description: Número de guía de la transportadora (coincidencia exacta). }
        - { name: search, in: query, schema: { type: string }, description: Nombre del destinatario (contiene). }
        - { name: dateFrom, in: query, schema: { type: string, format: date-time } }
        - { name: dateTo, in: query, schema: { type: string, format: date-time } }
      responses:
        '200':
          description: Página de envíos
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  data:
                    type: object
                    properties:
                      items: { type: array, items: { $ref: '#/components/schemas/Shipment' } }
                      nextCursor: { type: string, nullable: true }
                      total: { type: integer }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/ForbiddenScope' }
        '422': { $ref: '#/components/responses/Validation' }

  /api/v1/envios/bulk:
    post:
      tags: [Envíos]
      summary: Crear envíos en lote (1–50)
      description: |
        **Scope:** `shipments:write`. Idempotente. Body `{items: [...]}` o un array. Si algún ítem
        no pasa la validación, `422` sin crear nada (`details: [{index, issues}]`). Luego se genera
        la guía de cada ítem (5 en paralelo); los que fallan van en `failed` con el mismo error v1
        que daría la creación individual y no dejan borradores.
        HTTP `201` si salió al menos una guía; `200` con `created: []` si fallaron todas.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - type: object
                  required: [items]
                  properties:
                    items: { type: array, minItems: 1, maxItems: 50, items: { $ref: '#/components/schemas/CreateShipment' } }
                - type: array
                  minItems: 1
                  maxItems: 50
                  items: { $ref: '#/components/schemas/CreateShipment' }
      responses:
        '201':
          description: Resultado del lote
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BulkResultEnvelope' }
        '200':
          description: Ninguna guía salió (revisar `failed`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BulkResultEnvelope' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/ForbiddenScope' }
        '409': { $ref: '#/components/responses/IdempotencyConflict' }
        '422': { $ref: '#/components/responses/Validation' }
        '429': { $ref: '#/components/responses/RateLimitedOrSandboxLimit' }

  /api/v1/envios/{id}:
    get:
      tags: [Envíos]
      summary: Detalle de un envío
      description: '**Scope:** `shipments:read`. DTO + eventos (más reciente primero).'
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      responses:
        '200':
          description: Envío
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    allOf:
                      - $ref: '#/components/schemas/Shipment'
                      - type: object
                        properties:
                          events: { type: array, items: { $ref: '#/components/schemas/TrackingEvent' } }
        '404': { $ref: '#/components/responses/NotFound' }

  /api/v1/envios/{id}/etiqueta:
    get:
      tags: [Envíos]
      summary: Etiqueta (PDF)
      description: |
        **Scope:** `shipments:read`. Si la etiqueta oficial de la transportadora aún no estaba lista
        al crear, se vuelve a pedir aquí. El header `X-Enviala-Label-Source` dice si el PDF es la
        etiqueta de la transportadora (`carrier`) o la etiqueta propia de envíala (`enviala`).
        Consultarla no marca el envío como impreso.
      parameters:
        - { $ref: '#/components/parameters/Id' }
        - { name: formato, in: query, schema: { type: string, enum: ['10x15', carta], default: '10x15' }, description: 'Otro valor → 422.' }
      responses:
        '200':
          description: PDF
          headers:
            X-Enviala-Label-Source: { schema: { type: string, enum: [carrier, enviala] } }
            X-Label-Count: { schema: { type: integer } }
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }
        '422': { $ref: '#/components/responses/Validation' }

  /api/v1/envios/{id}/cancelar:
    post:
      tags: [Envíos]
      summary: Cancelar un envío
      description: |
        **Scope:** `shipments:write`. Con guía y antes de la recogida (`PENDING_PICKUP`,
        `PREPARADO_PARA_TRANSPORTADORA`): se anula en la transportadora y, si fue prepago, se
        reembolsa exactamente lo cobrado (`refund`). `DRAFT`: se anula en envíala. Ya recogido,
        en tránsito o cancelado, o si la transportadora no lo permite → `409 conflict`.
        Caída de la transportadora → `502`. Si la transportadora no anula por API se anula en
        envíala y `carrierNote` lo indica. Con key TEST solo afecta envíos de prueba.
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      responses:
        '200':
          description: Envío cancelado
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    allOf:
                      - $ref: '#/components/schemas/Shipment'
                      - type: object
                        properties:
                          refund: { type: number, description: 'Solo si se reembolsó algo.' }
                          carrierNote: { type: string }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }
        '502': { $ref: '#/components/responses/CarrierUnavailable' }

  /api/v1/envios/{id}/eventos:
    get:
      tags: [Rastreo]
      summary: Eventos de rastreo (autenticado)
      description: '**Scope:** `tracking:read`. LIVE refresca con la transportadora si hace más de 30 min. Orden: más reciente primero.'
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      responses:
        '200':
          description: Eventos
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      currentStatus: { $ref: '#/components/schemas/ShipmentStatus' }
                      events: { type: array, items: { $ref: '#/components/schemas/TrackingEvent' } }
        '404': { $ref: '#/components/responses/NotFound' }

  /api/v1/envios/{id}/simular:
    post:
      tags: [Envíos]
      summary: (Sandbox) Simular el avance de un envío de prueba
      description: |
        **Solo keys TEST** (con LIVE → `403 test_mode_only`). **Scope:** `shipments:write`.
        Registra el evento, mueve el estado y dispara a tus endpoints TEST el webhook
        correspondiente (`PICKED_UP` → `envio.recogido`, `IN_TRANSIT`/`OUT_FOR_DELIVERY` →
        `envio.en_camino`, `DELIVERED` → `envio.entregado`, `RETURNED` → `envio.devuelto`;
        `FAILED_ATTEMPT` abre una novedad de prueba y emite `envio.novedad`; resolver esa novedad
        con `REAGENDAR` emite `envio.reprogramado`). No toca wallet, liquidación ni avisa al destinatario.
        Un envío en estado final o en borrador → `409`.
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [status]
              properties:
                status: { type: string, enum: [PICKED_UP, IN_TRANSIT, OUT_FOR_DELIVERY, DELIVERED, FAILED_ATTEMPT, RETURNED_IN_TRANSIT, RETURNED] }
      responses:
        '200':
          description: Envío actualizado (DTO + eventos)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShipmentEnvelope' }
        '403':
          description: Key LIVE (`test_mode_only`) o sin scope
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }
        '422': { $ref: '#/components/responses/Validation' }

  /api/v1/envios/{id}/novedades:
    get:
      tags: [Novedades]
      summary: Novedades de un envío
      description: '**Scope:** `novelties:read`. Envío inexistente o de otro comercio/modo → 404.'
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      responses:
        '200':
          description: Novedades
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { type: object, properties: { items: { type: array, items: { $ref: '#/components/schemas/Novelty' } } } }
        '404': { $ref: '#/components/responses/NotFound' }

  /api/v1/envios/{guia}/tracking:
    get:
      tags: [Rastreo]
      summary: Rastreo público por número de guía (sin API key)
      description: |
        Para mostrarle el estado al comprador sin exponer tu key. Solo devuelve estado, fecha
        estimada y eventos (sin datos personales). Tope por IP → `429` con `Retry-After`.
      security: []
      parameters:
        - { name: guia, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: Estado
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      trackingNumber: { type: string }
                      status: { $ref: '#/components/schemas/ShipmentStatus' }
                      estimatedDelivery: { type: string, format: date-time, nullable: true }
                      events: { type: array, items: { $ref: '#/components/schemas/TrackingEvent' } }
        '404': { $ref: '#/components/responses/NotFound' }
        '429': { $ref: '#/components/responses/RateLimited' }

  # ─── Cotización ─────────────────────────────────────────────────────────────
  /api/v1/cotizar:
    post:
      tags: [Cotización]
      summary: Cotizar el flete
      description: |
        **Scope:** `shipments:read`. `total` es **todo incluido** (flete, sobre-flete y comisión de
        recaudo). Por cada transportadora en vivo que no cotizó, `unavailable` da el motivo
        (`no_coverage` = no cubre/rechazó; `error` = no respondió). Nunca responde un 404 global por
        zona. Ciudad y departamento se normalizan (tildes, «Bogota», «Cundinamarca»).
        Key TEST: precios simulados deterministas (`simulated: true`).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [destinationCity, destinationDept, weight, codAmount]
              properties:
                destinationCity: { type: string, example: Bogotá }
                destinationDept: { type: string, example: Bogotá D.C. }
                destinationAddress: { type: string, description: 'Dirección de calle. **Obligatoria en la práctica para ENVIALA_EXPRESS.**', example: 'Carrera 15 # 93-47' }
                weight: { type: number, exclusiveMinimum: true, minimum: 0, maximum: 30 }
                shipmentType: { type: string, enum: [COD, PREPAID], default: COD }
                codAmount: { type: integer, minimum: 0, maximum: 10000000, description: 'PREPAID ⇒ 0; COD ⇒ > 0. Pesos enteros.' }
                bodegaId: { type: string, format: uuid }
      responses:
        '200':
          description: Cotizaciones
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      quotes: { type: array, items: { $ref: '#/components/schemas/Quote' } }
                      unavailable:
                        type: array
                        items:
                          type: object
                          properties:
                            carrierSlug: { $ref: '#/components/schemas/CarrierSlug' }
                            reason: { type: string, enum: [no_coverage, error] }
                            message: { type: string }
                      isTest: { type: boolean, description: Solo con key TEST. }
        '400': { $ref: '#/components/responses/InvalidBody' }
        '422': { $ref: '#/components/responses/Validation' }

  /api/v1/transportadoras:
    get:
      tags: [Cotización]
      summary: Transportadoras activas
      description: '**Scope:** `shipments:read`.'
      responses:
        '200':
          description: Lista
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      items:
                        type: array
                        items:
                          type: object
                          properties:
                            slug: { $ref: '#/components/schemas/CarrierSlug' }
                            name: { type: string }
                            logoUrl: { type: string, nullable: true }

  /api/v1/cobertura:
    get:
      tags: [Cotización]
      summary: Cobertura de un destino
      description: |
        **Scope:** `shipments:read`. `details[].mode`: `tariff` (tarifa de la zona) o `live` (la
        transportadora confirma y pone precio en `/cotizar`; p. ej. ENVIALA_EXPRESS solo Bogotá).
        Respeta las transportadoras desactivadas.
      parameters:
        - { name: ciudad, in: query, required: true, schema: { type: string } }
        - { name: departamento, in: query, required: true, schema: { type: string } }
      responses:
        '200':
          description: Cobertura
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      covered: { type: boolean }
                      ciudad: { type: string }
                      departamento: { type: string }
                      zone: { type: object, nullable: true, properties: { id: { type: string }, name: { type: string } } }
                      carriers: { type: array, items: { $ref: '#/components/schemas/CarrierSlug' } }
                      details:
                        type: array
                        items:
                          type: object
                          properties:
                            carrierSlug: { $ref: '#/components/schemas/CarrierSlug' }
                            mode: { type: string, enum: [tariff, live] }
        '422': { $ref: '#/components/responses/Validation' }

  # ─── Manifiestos ────────────────────────────────────────────────────────────
  /api/v1/manifiestos:
    post:
      tags: [Manifiestos]
      summary: Crear manifiesto(s)
      description: |
        **Scope:** `manifests:write`. Idempotente. Agrupa por transportadora. Acepta guías sin
        manifiesto o que estén en un manifiesto **abierto** (p. ej. el automático del día: se
        mueven). Las de un manifiesto cerrado no. Cada guía generada entra sola al manifiesto
        abierto del día de su transportadora y bodega. Key TEST: simulado (no se guarda).
      parameters: [ { $ref: '#/components/parameters/IdempotencyKey' } ]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [shipmentIds]
              properties:
                shipmentIds: { type: array, items: { type: string } }
      responses:
        '201':
          description: Manifiestos creados
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      manifests: { type: array, items: { $ref: '#/components/schemas/Manifest' } }
                      count: { type: integer }
        '409': { $ref: '#/components/responses/IdempotencyConflict' }
        '422': { $ref: '#/components/responses/Validation' }
    get:
      tags: [Manifiestos]
      summary: Listar manifiestos (cursor)
      description: '**Scope:** `manifests:read`. Key TEST: lista vacía.'
      parameters:
        - { name: cursor, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
      responses:
        '200':
          description: Página
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      items: { type: array, items: { $ref: '#/components/schemas/Manifest' } }
                      nextCursor: { type: string, nullable: true }
        '422': { $ref: '#/components/responses/Validation' }

  /api/v1/manifiestos/{id}:
    get:
      tags: [Manifiestos]
      summary: Detalle de un manifiesto
      description: '**Scope:** `manifests:read`.'
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      responses:
        '200':
          description: Manifiesto con sus envíos
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    allOf:
                      - $ref: '#/components/schemas/Manifest'
                      - type: object
                        properties:
                          shipments: { type: array, items: { $ref: '#/components/schemas/Shipment' } }
        '404': { $ref: '#/components/responses/NotFound' }

  /api/v1/manifiestos/{id}/pdf:
    get:
      tags: [Manifiestos]
      summary: PDF del manifiesto
      description: '**Scope:** `manifests:read`.'
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      responses:
        '200':
          description: PDF
          content: { application/pdf: { schema: { type: string, format: binary } } }
        '404': { $ref: '#/components/responses/NotFound' }

  /api/v1/manifiestos/{id}/cerrar:
    post:
      tags: [Manifiestos]
      summary: Cerrar manifiesto (entregado a la transportadora)
      description: '**Scope:** `manifests:write`. Idempotente.'
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      responses:
        '200':
          description: Manifiesto cerrado
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/Manifest' }
        '404': { $ref: '#/components/responses/NotFound' }

  # ─── Recogidas ──────────────────────────────────────────────────────────────
  /api/v1/recogidas:
    post:
      tags: [Recogidas]
      summary: Programar una recogida
      description: |
        **Scope:** `pickups:write`. **ENVIALA_EXPRESS**: se programa con la transportadora
        (mensajero real); puede correr la fecha por el corte o un día no hábil (`rescheduled`,
        `scheduleMessage`). **Otras transportadoras**: queda registrada en envíala y el equipo la
        coordina: `carrierScheduled: false` (la transportadora no fue notificada por API).
        Idempotente con `Idempotency-Key`. Una recogida abierta por comercio, transportadora y día:
        si ya existe se responde **200** con esa recogida (`deduplicated: true`), sin volver a
        pedirla. Key TEST: simulada (no se guarda ni se notifica).
      parameters: [ { $ref: '#/components/parameters/IdempotencyKey' } ]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [carrierSlug]
              properties:
                carrierSlug: { type: string, enum: [SERVIENTREGA, ENVIA, COORDINADORA, TCC, INTER_RAPIDISIMO, ENVIALA_EXPRESS, GOOENVIOS] }
                scheduledAt: { type: string, format: date-time, description: 'Fecha deseada (por defecto: ahora).' }
                note: { type: string, maxLength: 500 }
      responses:
        '201':
          description: Recogida creada
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/Pickup' }
        '200':
          description: Ya había una recogida abierta ese día para esa transportadora (`deduplicated`)
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    allOf:
                      - $ref: '#/components/schemas/Pickup'
                      - type: object
                        properties: { deduplicated: { type: boolean, example: true } }
        '403': { $ref: '#/components/responses/ForbiddenScope' }
        '409': { $ref: '#/components/responses/IdempotencyConflict' }
        '422': { $ref: '#/components/responses/Validation' }
        '502': { $ref: '#/components/responses/CarrierUnavailable' }
    get:
      tags: [Recogidas]
      summary: Listar recogidas
      description: '**Scope:** `pickups:read`. Últimas 100. Key TEST: lista vacía.'
      responses:
        '200':
          description: Recogidas + ventana de Envíala Express de hoy
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      items: { type: array, items: { $ref: '#/components/schemas/Pickup' } }
                      express:
                        type: object
                        properties:
                          date: { type: string, format: date }
                          sameDay: { type: boolean }
                          text: { type: string }
                          cutoffLabel: { type: string }

  # ─── Novedades ──────────────────────────────────────────────────────────────
  /api/v1/novedades:
    get:
      tags: [Novedades]
      summary: Listar novedades
      description: '**Scope:** `novelties:read`.'
      parameters:
        - { name: status, in: query, schema: { type: string, enum: [open, resolved] }, description: 'Otro valor → 422.' }
      responses:
        '200':
          description: Novedades
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { type: object, properties: { items: { type: array, items: { $ref: '#/components/schemas/Novelty' } } } }
        '422': { $ref: '#/components/responses/Validation' }

  /api/v1/novedades/{id}/resolver:
    post:
      tags: [Novedades]
      summary: Resolver una novedad
      description: |
        **Scope:** `novelties:write`. Queda registrada en envíala y el equipo la gestiona con la
        transportadora: **ninguna transportadora la recibe automáticamente por API**
        (`carrierNotified: false`). Ya resuelta → `409`.
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [action]
              properties:
                action: { type: string, enum: [REAGENDAR, DEVOLVER, INSISTIR] }
                note: { type: string }
      responses:
        '200':
          description: Novedad resuelta
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    allOf:
                      - $ref: '#/components/schemas/Novelty'
                      - type: object
                        properties:
                          carrierNotified: { type: boolean, example: false }
                          carrierNote: { type: string }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }
        '422': { $ref: '#/components/responses/Validation' }

  # ─── Score ──────────────────────────────────────────────────────────────────
  /api/v1/destinatarios/{telefono}/score:
    get:
      tags: [Score]
      summary: Score de un destinatario (PREMIUM)
      description: '**Scope:** `score:read`. Medido para cobro. `phone` vuelve en forma local (10 dígitos, sin 57).'
      parameters:
        - { name: telefono, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: Score
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      phone: { type: string, example: '3001234567' }
                      score: { type: number }
                      level: { type: string }
                      totalShipments: { type: integer }
                      delivered: { type: integer }
                      returned: { type: integer }
                      deliveryRate: { type: number, nullable: true }
                      isBlacklisted: { type: boolean }
                      recommendation: { type: string }
        '422': { $ref: '#/components/responses/Validation' }

  # ─── Cuenta (solo lectura) ──────────────────────────────────────────────────
  /api/v1/cuenta:
    get:
      tags: [Cuenta]
      summary: Datos de la cuenta
      description: '**Scope:** `wallet:read`.'
      responses:
        '200':
          description: Cuenta
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      businessName: { type: string, nullable: true }
                      email: { type: string }
                      plan: { type: string }

  /api/v1/saldo:
    get:
      tags: [Cuenta]
      summary: Saldo del wallet
      description: '**Scope:** `wallet:read`. Key TEST: ceros con `isTest: true`.'
      responses:
        '200':
          description: Saldo
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      balance: { type: number }
                      available: { type: number }
                      frozenBalance: { type: number }
                      currency: { type: string, example: COP }
                      isTest: { type: boolean }

  /api/v1/movimientos:
    get:
      tags: [Cuenta]
      summary: Movimientos del wallet (cursor)
      description: '**Scope:** `wallet:read`. `type` desconocido → 422. Key TEST: vacío.'
      parameters:
        - { name: cursor, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, maximum: 100 } }
        - name: type
          in: query
          schema: { type: string, enum: [TOPUP, SHIPMENT_CHARGE, COD_CREDIT, INSURANCE_CHARGE, RETURN_CHARGE, REFUND, WITHDRAWAL, ADJUSTMENT, ADVANCE, ADVANCE_RECOVERY, PURCHASE, REWARD_CREDIT, COMMUNITY_COMMISSION] }
      responses:
        '200':
          description: Movimientos
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      items: { type: array, items: { type: object } }
                      nextCursor: { type: string, nullable: true }
        '422': { $ref: '#/components/responses/Validation' }

  /api/v1/cartera:
    get:
      tags: [Cuenta]
      summary: Cartera (resumen + detalle por envío)
      description: '**Scope:** `wallet:read`. Key TEST: vacío.'
      parameters:
        - { name: page, in: query, schema: { type: integer, minimum: 1 } }
        - { name: limit, in: query, schema: { type: integer, maximum: 100 } }
      responses:
        '200':
          description: Cartera
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      resumen: { type: object, nullable: true }
                      items: { type: array, items: { type: object } }
                      total: { type: integer }

  /api/v1/landings/{slug}/lead:
    post:
      tags: [Envíos]
      summary: Registrar un lead de una landing propia
      description: |
        Requiere API key (sin scope). Solo landings **publicadas del mismo comercio** (otra → 404).
        Key TEST: simulado (no crea pedido ni evento de conversión).
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [recipientName, recipientPhone, recipientAddress, recipientCity, recipientDept, codAmount]
              properties:
                recipientName: { type: string }
                recipientPhone: { type: string }
                recipientAddress: { type: string }
                recipientCity: { type: string }
                recipientDept: { type: string }
                codAmount: { type: number }
                fbclid: { type: string }
                ttclid: { type: string }
                utmSource: { type: string }
                utmCampaign: { type: string }
      responses:
        '201':
          description: Lead registrado
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      shipmentId: { type: string }
                      message: { type: string }
                      isTest: { type: boolean }
        '404': { $ref: '#/components/responses/NotFound' }
        '422': { $ref: '#/components/responses/Validation' }

  # ─── Webhooks ───────────────────────────────────────────────────────────────
  /api/v1/webhooks:
    post:
      tags: [Webhooks]
      summary: Registrar un endpoint
      description: |
        **Scope:** `webhooks:manage`. URL https que resuelva a una IP **pública** (loopback, redes
        privadas, link-local, metadata de la nube, CGNAT e IPv6 equivalentes → 422; se vuelve a
        validar en cada entrega). La misma URL dos veces → `409`. El `secret` se muestra **una
        sola vez**. Con key TEST el endpoint es `mode: TEST` y solo recibe eventos del sandbox.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url, events]
              properties:
                url: { type: string, format: uri, example: 'https://tu-dominio.com/webhooks/enviala' }
                events: { type: array, minItems: 1, items: { $ref: '#/components/schemas/WebhookEvent' } }
      responses:
        '201':
          description: Endpoint creado (incluye `secret`)
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    allOf:
                      - $ref: '#/components/schemas/WebhookEndpoint'
                      - type: object
                        properties: { secret: { type: string } }
        '409': { $ref: '#/components/responses/Conflict' }
        '422': { $ref: '#/components/responses/Validation' }
    get:
      tags: [Webhooks]
      summary: Listar endpoints
      description: '**Scope:** `webhooks:manage`. Solo los del modo de la key.'
      responses:
        '200':
          description: Endpoints (sin secret)
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { type: object, properties: { items: { type: array, items: { $ref: '#/components/schemas/WebhookEndpoint' } } } }

  /api/v1/webhooks/{id}:
    delete:
      tags: [Webhooks]
      summary: Eliminar un endpoint
      description: '**Scope:** `webhooks:manage`.'
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      responses:
        '200': { description: Eliminado }
        '404': { $ref: '#/components/responses/NotFound' }

  /api/v1/webhooks/{id}/entregas:
    get:
      tags: [Webhooks]
      summary: Historial de entregas de un endpoint
      description: '**Scope:** `webhooks:manage`. Últimas 100.'
      parameters: [ { $ref: '#/components/parameters/Id' } ]
      responses:
        '200':
          description: Entregas
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { type: object, properties: { items: { type: array, items: { $ref: '#/components/schemas/WebhookDelivery' } } } }
        '404': { $ref: '#/components/responses/NotFound' }

  /api/v1/webhooks/{id}/entregas/{deliveryId}/reintentar:
    post:
      tags: [Webhooks]
      summary: Reintentar una entrega
      description: '**Scope:** `webhooks:manage`. La deja pendiente para ya y reinicia los intentos.'
      parameters:
        - { $ref: '#/components/parameters/Id' }
        - { name: deliveryId, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: Entrega reencolada
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/WebhookDelivery' }
        '404': { $ref: '#/components/responses/NotFound' }

components:
  securitySchemes:
    ApiKeyAuth: { type: apiKey, in: header, name: X-API-Key }

  parameters:
    Id: { name: id, in: path, required: true, schema: { type: string } }
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      schema: { type: string, maxLength: 255 }
      description: Única por operación (p. ej. tu id de pedido). Ver Idempotencia.

  headers:
    RateLimitSet:
      X-RateLimit-Limit: { schema: { type: integer, example: 120 } }
      X-RateLimit-Remaining: { schema: { type: integer } }
      X-RateLimit-Reset: { schema: { type: integer }, description: Epoch en segundos }

  responses:
    InvalidBody:
      description: JSON malformado o body no-objeto (`invalid_body`)
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    Unauthorized:
      description: '`unauthorized`'
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    ForbiddenScope:
      description: '`forbidden_scope`'
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    NotFound:
      description: '`not_found`'
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    Conflict:
      description: '`conflict`'
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    IdempotencyConflict:
      description: '`idempotency_key_reuse` o `idempotency_in_progress`'
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    InsufficientBalance:
      description: '`insufficient_balance` (`details: {available, required, shipmentId?, status?}`)'
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    Validation:
      description: '`validation_error` (`details.issues`)'
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            success: false
            error:
              code: validation_error
              message: Datos inválidos
              details:
                issues:
                  - { path: recipient.phone, message: Debe ser un celular colombiano de 10 dígitos que empiece por 3 (se acepta +57) }
    ValidationOrCarrierRejected:
      description: '`validation_error` o `carrier_rejected`'
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            success: false
            error:
              code: carrier_rejected
              message: Envíala Express no pudo ubicar la dirección del destinatario. Escríbela más completa (vía, número y complemento) o agrega un punto de referencia.
              details: { carrier: ENVIALA_EXPRESS, carrierCode: PTN-VAL-011, field: recipient.address, shipmentId: 3f0c…, status: CANCELLED }
    RateLimitedOrSandboxLimit:
      description: '`rate_limited` o (key TEST) `sandbox_limit`'
      headers:
        Retry-After: { schema: { type: integer } }
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    RateLimited:
      description: '`rate_limited`'
      headers:
        Retry-After: { schema: { type: integer } }
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    Internal:
      description: '`internal_error`'
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    CarrierUnavailable:
      description: '`carrier_unavailable` (`details: {carrier, carrierCode, …}`); reintentable'
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  schemas:
    Error:
      type: object
      properties:
        success: { type: boolean, example: false }
        error:
          type: object
          required: [code, message]
          properties:
            code:
              type: string
              enum: [unauthorized, forbidden_scope, not_found, validation_error, rate_limited, idempotency_key_reuse, idempotency_in_progress, insufficient_balance, internal_error, conflict, carrier_rejected, carrier_unavailable, invalid_body, test_mode_only, sandbox_limit]
            message: { type: string }
            details:
              description: 'Depende del código; en validation_error → {issues: [{path, message}]}.'
              oneOf:
                - type: object
                  properties:
                    issues:
                      type: array
                      items: { type: object, properties: { path: { type: string }, message: { type: string } } }
                - type: object
                - type: array
                  items: { type: object }

    CarrierSlug:
      type: string
      enum: [SERVIENTREGA, ENVIA, COORDINADORA, TCC, INTER_RAPIDISIMO, ENVIALA_EXPRESS, GOOENVIOS, ENVIALA_PRUEBA]
      description: '`ENVIALA_EXPRESS` = mismo día, solo Bogotá. `ENVIALA_PRUEBA` = ficticio, solo cuentas de prueba.'

    ShipmentStatus:
      type: string
      enum: [DRAFT, PENDING_PICKUP, PREPARADO_PARA_TRANSPORTADORA, PICKED_UP, IN_TRANSIT, OUT_FOR_DELIVERY, DELIVERED, FAILED_ATTEMPT, RETURNED_IN_TRANSIT, RETURNED, LOST, CANCELLED]

    WebhookEvent:
      type: string
      enum: [envio.creado, envio.recogido, envio.en_camino, envio.entregado, envio.devuelto, envio.novedad, envio.reprogramado, recaudo.liquidado, adelanto.aprobado, adelanto.saldado]
      description: |
        Cuándo sale cada evento:
        - `envio.creado`: se generó la guía (API, lote o panel).
        - `envio.recogido`: la transportadora recogió el paquete (estado `PICKED_UP`).
        - `envio.en_camino`: en tránsito o en reparto (`IN_TRANSIT`, `OUT_FOR_DELIVERY`).
        - `envio.entregado`: `DELIVERED`.
        - `envio.devuelto`: `RETURNED`.
        - `envio.novedad`: se abrió una novedad de entrega.
        - `envio.reprogramado`: una novedad quedó resuelta con la acción `REAGENDAR`, por
          cualquier camino (API, panel, el comprador por WhatsApp, la llamada de Amelia o la
          aprobación de la solución por la transportadora). Una vez por resolución.
        - `recaudo.liquidado`: el recaudo COD del envío se liquidó al wallet.
        - `adelanto.aprobado` / `adelanto.saldado`: adelanto de saldo aprobado / recuperado.
        Un endpoint solo recibe los eventos de su lista `events` (los nuevos no se agregan solos).

    CreateShipment:
      type: object
      required: [carrierSlug, codAmount, recipient, product]
      properties:
        carrierSlug: { $ref: '#/components/schemas/CarrierSlug' }
        shipmentType: { type: string, enum: [COD, PREPAID], default: COD }
        codAmount: { type: integer, minimum: 0, maximum: 10000000, description: 'Pesos enteros. PREPAID ⇒ 0; COD ⇒ > 0.' }
        insuranceTier: { type: string, enum: [NONE, BASIC, PRO], default: NONE, description: Solo aplica a COD. }
        recipient:
          type: object
          required: [name, phone, address, city, department]
          properties:
            name: { type: string, minLength: 2, maxLength: 200 }
            phone: { type: string, description: 'Celular colombiano de 10 dígitos que empieza por 3; se acepta +57/57/espacios y se guarda normalizado.' }
            address: { type: string, minLength: 5, maxLength: 300 }
            city: { type: string }
            department: { type: string }
            zip: { type: string }
            email: { type: string, format: email }
        product:
          type: object
          required: [description, weight, declaredValue]
          properties:
            description: { type: string, minLength: 2, maxLength: 200 }
            weight: { type: number, exclusiveMinimum: true, minimum: 0, maximum: 30, description: kg }
            declaredValue: { type: integer, minimum: 1, description: Pesos enteros. }
            dimensions:
              type: object
              properties: { length: { type: number }, width: { type: number }, height: { type: number } }
        externalId: { type: string, description: 'Tu número de pedido (filtrable en GET /envios y presente en los webhooks).' }
        deliveryNotes: { type: string, maxLength: 1000 }
        bodegaId: { type: string, format: uuid }
        productId: { type: string, format: uuid }
        variantId: { type: string, format: uuid }
        fbclid: { type: string }
        ttclid: { type: string }
        utmSource: { type: string }
        utmCampaign: { type: string }
        utmAdset: { type: string }
        utmAd: { type: string }

    Shipment:
      type: object
      description: DTO v1 del envío (montos en number; nunca datos internos).
      properties:
        id: { type: string }
        externalId: { type: string, nullable: true }
        trackingNumber: { type: string, nullable: true }
        carrierSlug: { $ref: '#/components/schemas/CarrierSlug' }
        status: { $ref: '#/components/schemas/ShipmentStatus' }
        shipmentType: { type: string, enum: [COD, PREPAID] }
        codAmount: { type: number }
        shippingCost: { type: number }
        insuranceTier: { type: string, enum: [NONE, BASIC, PRO] }
        insuranceCost: { type: number }
        recipient:
          type: object
          properties:
            name: { type: string }
            phone: { type: string }
            address: { type: string }
            city: { type: string }
            department: { type: string }
            email: { type: string, description: Solo si se envió. }
        product:
          type: object
          properties:
            description: { type: string }
            weight: { type: number }
            declaredValue: { type: number }
        deliveryNotes: { type: string, nullable: true }
        labelUrl: { type: string, nullable: true }
        estimatedDelivery: { type: string, format: date-time, nullable: true }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
        deliveredAt: { type: string, format: date-time, nullable: true }
        cancelledAt: { type: string, format: date-time, nullable: true }

    ShipmentEnvelope:
      type: object
      properties:
        success: { type: boolean, example: true }
        data: { $ref: '#/components/schemas/Shipment' }

    BulkResultEnvelope:
      type: object
      properties:
        success: { type: boolean }
        data:
          type: object
          properties:
            created: { type: array, items: { $ref: '#/components/schemas/Shipment' } }
            failed:
              type: array
              items:
                type: object
                properties:
                  index: { type: integer }
                  externalId: { type: string }
                  error:
                    type: object
                    properties:
                      code: { type: string }
                      message: { type: string }
                      details: { type: object }

    TrackingEvent:
      type: object
      properties:
        status: { type: string, description: 'Estado reportado por la transportadora (texto del carrier).' }
        description: { type: string }
        location: { type: string, nullable: true }
        occurredAt: { type: string, format: date-time }

    Quote:
      type: object
      properties:
        carrierSlug: { $ref: '#/components/schemas/CarrierSlug' }
        displayName: { type: string }
        logoUrl: { type: string, nullable: true }
        total: { type: number, description: Todo incluido. }
        estimatedDays: { type: integer, nullable: true }
        deliveryRate: { type: number, nullable: true, description: 'Efectividad real (solo con ≥20 envíos terminados).' }
        isCheapest: { type: boolean }
        isFastest: { type: boolean }
        simulated: { type: boolean, description: Solo con key TEST. }
        cutoff:
          type: object
          description: Solo ENVIALA_EXPRESS.
          properties:
            deliveryDate: { type: string, format: date, description: Fecha de entrega si se crea ahora (hora Bogotá). }
            sameDay: { type: boolean }
            orderBefore: { type: string, format: date-time, nullable: true, description: 'Hasta cuándo pedir para mantener la entrega de hoy (null si ya no es hoy).' }
            rule: { type: string }

    Manifest:
      type: object
      properties:
        id: { type: string }
        carrierSlug: { $ref: '#/components/schemas/CarrierSlug' }
        status: { type: string, enum: [OPEN, CLOSED] }
        totalGuias: { type: integer }
        totalPeso: { type: number }
        totalCod: { type: number }
        closedAt: { type: string, format: date-time, nullable: true }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }

    Pickup:
      type: object
      properties:
        id: { type: string }
        carrierSlug: { $ref: '#/components/schemas/CarrierSlug' }
        status: { type: string, enum: [REQUESTED, SCHEDULED, DONE, CANCELLED] }
        scheduledAt: { type: string, format: date-time }
        carrierScheduled: { type: boolean, description: '`true` = la transportadora la tiene programada; `false` = registro en envíala.' }
        carrierStatus: { type: string, nullable: true }
        rescheduled: { type: boolean }
        scheduleMessage: { type: string, nullable: true }
        note: { type: string, nullable: true }
        createdAt: { type: string, format: date-time }
        message: { type: string }
        isTest: { type: boolean }

    Novelty:
      type: object
      properties:
        id: { type: string }
        shipmentId: { type: string }
        type: { type: string, enum: [DIRECCION_ERRADA, CLIENTE_AUSENTE, RECHAZADO, OTRO] }
        status: { type: string, enum: [OPEN, RESOLVED] }
        action: { type: string, nullable: true }
        note: { type: string, nullable: true }
        createdAt: { type: string, format: date-time }
        resolvedAt: { type: string, format: date-time, nullable: true }

    WebhookEndpoint:
      type: object
      properties:
        id: { type: string }
        url: { type: string }
        events: { type: array, items: { $ref: '#/components/schemas/WebhookEvent' } }
        enabled: { type: boolean }
        mode: { type: string, enum: [LIVE, TEST] }
        createdAt: { type: string, format: date-time }

    WebhookDelivery:
      type: object
      properties:
        id: { type: string }
        endpointId: { type: string }
        event: { $ref: '#/components/schemas/WebhookEvent' }
        status: { type: string, enum: [PENDING, SUCCESS, FAILED] }
        attempts: { type: integer }
        lastAttemptAt: { type: string, format: date-time, nullable: true }
        responseStatus: { type: integer, nullable: true }
        responseBody: { type: string, nullable: true, maxLength: 200 }
        nextRetryAt: { type: string, format: date-time, nullable: true }
        createdAt: { type: string, format: date-time }

    WebhookPayload:
      type: object
      description: |
        Cuerpo de cada entrega. Siempre trae `event`, `eventId` y `occurredAt`. Ejemplos:

        **envio.creado / envio.recogido / envio.en_camino / envio.entregado / envio.devuelto**
        ```json
        {"id":"3f0c…","trackingNumber":"BX104233","externalId":"MARCA-100231","carrierSlug":"ENVIALA_EXPRESS",
         "status":"DELIVERED","livemode":true,"event":"envio.entregado","eventId":"9b1e…","occurredAt":"2026-12-02T20:14:03.120Z"}
        ```
        **envio.novedad**
        ```json
        {"id":"3f0c…","trackingNumber":"BX104233","externalId":"MARCA-100231","carrierSlug":"ENVIALA_EXPRESS",
         "status":"FAILED_ATTEMPT","livemode":true,"noveltyId":"77aa…","shipmentId":"3f0c…","type":"CLIENTE_AUSENTE",
         "note":"No estaba","event":"envio.novedad","eventId":"…","occurredAt":"…"}
        ```
        **envio.reprogramado**
        ```json
        {"id":"3f0c…","trackingNumber":"BX104233","externalId":"MARCA-100231","carrierSlug":"ENVIALA_EXPRESS",
         "status":"FAILED_ATTEMPT","livemode":true,
         "novelty":{"id":"77aa…","type":"CLIENTE_AUSENTE","action":"REAGENDAR","note":"el martes en la tarde",
                    "resolvedAt":"2026-12-02T21:03:11.402Z","scheduledDate":"2026-12-09","slot":"tarde"},
         "event":"envio.reprogramado","eventId":"…","occurredAt":"…"}
        ```
        (`scheduledDate` y `slot` solo si se conocen.)
        **recaudo.liquidado**
        ```json
        {"id":"3f0c…","trackingNumber":"BX104233","externalId":"MARCA-100231","carrierSlug":"ENVIALA_EXPRESS",
         "status":"DELIVERED","livemode":true,"shipmentId":"3f0c…","settlementId":"s-12","delta":71500,
         "shipmentStatus":"DELIVERED","event":"recaudo.liquidado","eventId":"…","occurredAt":"…"}
        ```
        **adelanto.aprobado / adelanto.saldado** (son de la cuenta, no de un envío: no traen campos de envío)
        ```json
        {"advanceId":"a1b2…","amount":500000,"event":"adelanto.aprobado","eventId":"…","occurredAt":"…"}
        {"advanceId":"a1b2…","amount":500000,"totalToRecover":525000,"event":"adelanto.saldado","eventId":"…","occurredAt":"…"}
        ```

        **Campos**
        - `id`: id del envío en envíala (el que devuelve `POST /envios`). `externalId`: tu número de
          pedido si lo enviaste al crear el envío; si no, `null`.
        - `status` (eventos de envío): `envio.creado` → normalmente `PENDING_PICKUP`;
          `envio.recogido` → `PICKED_UP`; `envio.en_camino` → `IN_TRANSIT` u `OUT_FOR_DELIVERY`;
          `envio.entregado` → `DELIVERED`; `envio.devuelto` → `RETURNED`. En `envio.novedad`,
          `envio.reprogramado` y `recaudo.liquidado` es el estado del envío en ese momento.
        - `livemode: false` = evento del sandbox (solo llega a endpoints TEST).
        - `envio.novedad`: `type` es `DIRECCION_ERRADA`, `CLIENTE_AUSENTE`, `RECHAZADO` u `OTRO`;
          `note` es texto libre de la transportadora (puede ser `null`); `shipmentId` = `id`.
        - `recaudo.liquidado`: `delta` = neto aplicado a tu wallet en pesos (recaudo menos flete y
          seguro); puede ser **negativo** (p. ej. una devolución en la que se cobra el flete).
          `shipmentStatus` = estado final liquidado (`DELIVERED`, `RETURNED` o `LOST`). En el
          sandbox, `settlementId` es `null` y llega además `"simulated": true`.
        - `adelanto.*`: `amount` = valor del adelanto; `totalToRecover` = total recuperado (adelanto + tarifa).

        **Buenas prácticas**
        - Casa el evento con tu pedido por `externalId` (o `id`) y deduplica por `eventId`.
        - Los eventos pueden llegar en desorden (p. ej. tras un reintento): usa `occurredAt` o
          consulta `GET /envios/{id}` para el estado actual.
        - Los webhooks **no** traen nombre, dirección ni teléfono del destinatario: para eso
          consulta `GET /envios/{id}`.
      properties:
        id: { type: string }
        trackingNumber: { type: string, nullable: true }
        externalId: { type: string, nullable: true }
        carrierSlug: { $ref: '#/components/schemas/CarrierSlug' }
        status: { type: string }
        livemode: { type: boolean }
        event: { $ref: '#/components/schemas/WebhookEvent' }
        eventId: { type: string }
        occurredAt: { type: string, format: date-time }
