openapi: 3.1.0
info:
  title: KaruGO Merchant API
  version: 1.0.0-draft
  summary: API pública de KaruGO Delivery para integradores (PDV, ERP y logística).
  description: |
    API REST para que sistemas de terceros operen tiendas en KaruGO Delivery:
    pedidos, catálogo, horarios y envíos bajo demanda.

    **Estado:** borrador del contrato v1. Puede cambiar antes de la versión estable.

    - Autenticación: OAuth 2.0 *client credentials* (`POST /oauth/token`).
    - Formato: JSON UTF-8. Fechas ISO 8601 en UTC. Montos enteros en guaraníes (`PYG`).
    - Paginación: parámetros `page` (desde 1) y `size` (máx. 100).
    - Errores: objeto `error` con `code`, `message` y `traceId`.
  contact:
    name: Equipo de Integraciones KaruGO
    url: https://developers.karugo.com.py/ayuda
servers:
  - url: https://merchant-api.karugo.com.py/v1
    description: Producción
  - url: https://sandbox.merchant-api.karugo.com.py/v1
    description: Sandbox
security:
  - oauth2: []
tags:
  - name: Autenticación
    description: Obtención de tokens de acceso con OAuth 2.0 (client credentials).
  - name: Tiendas
    description: Tiendas (restaurantes) autorizadas para su aplicación, estado de apertura y horarios.
  - name: Catálogo
    description: Categorías y productos del menú. Use `externalCode` para mapear los productos de su PDV.
  - name: Pedidos
    description: Detalle de pedidos y acciones del ciclo de vida (confirmar, preparar, despachar, cancelar).
  - name: Eventos
    description: |
      Cambios de estado de pedidos y envíos. Reciba eventos por **webhook** (recomendado) o por **polling**,
      y confírmelos siempre con `POST /events/acknowledgment`.
  - name: Envíos
    description: "**Beta.** Repartidores KaruGO bajo demanda para ventas hechas fuera de la app."
  - name: Sandbox
    description: Herramientas para pruebas. **Solo existen en el ambiente sandbox.**

paths:
  /oauth/token:
    post:
      tags: [Autenticación]
      operationId: createAccessToken
      summary: Obtener un token de acceso
      description: |
        Intercambia las credenciales de la aplicación por un token Bearer válido por 6 horas.
        Reutilice el token en todas las llamadas y renuévelo antes de que expire.
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [grant_type, client_id, client_secret]
              properties:
                grant_type:
                  type: string
                  enum: [client_credentials]
                client_id:
                  type: string
                  example: 9d4f8a2c-1b7e-4c55-9a51-0f3d2b6e8c11
                client_secret:
                  type: string
                  format: password
                scope:
                  type: string
                  description: Scopes separados por espacio. Si se omite, se otorgan todos los autorizados para la aplicación.
                  example: orders:read orders:write events:read
      responses:
        '200':
          description: Token emitido.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AccessToken'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          description: Credenciales inválidas.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error:
                  code: invalid_client
                  message: Las credenciales de la aplicación no son válidas.
                  traceId: 6f1c2a9e3b7d4e08

  /merchants:
    get:
      tags: [Tiendas]
      operationId: listMerchants
      summary: Listar tiendas autorizadas
      description: Devuelve las tiendas que autorizaron a su aplicación.
      security:
        - oauth2: ['merchant:read']
      parameters:
        - $ref: '#/components/parameters/Page'
        - $ref: '#/components/parameters/Size'
      responses:
        '200':
          description: Lista paginada de tiendas.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Pagination'
                  - type: object
                    properties:
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/MerchantSummary'
        '401':
          $ref: '#/components/responses/Unauthorized'

  /merchants/{merchantId}:
    get:
      tags: [Tiendas]
      operationId: getMerchant
      summary: Detalle de una tienda
      security:
        - oauth2: ['merchant:read']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
      responses:
        '200':
          description: Tienda.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Merchant'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  /merchants/{merchantId}/status:
    get:
      tags: [Tiendas]
      operationId: getMerchantStatus
      summary: Estado de apertura
      description: Indica si la tienda está recibiendo pedidos ahora y por qué.
      security:
        - oauth2: ['merchant:read']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
      responses:
        '200':
          description: Estado actual.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MerchantStatus'
        '404':
          $ref: '#/components/responses/NotFound'
    patch:
      tags: [Tiendas]
      operationId: updateMerchantStatus
      summary: Abrir o cerrar la tienda
      description: |
        Abre o cierra temporalmente la tienda para nuevos pedidos (por ejemplo, por exceso de demanda).
        El cierre no afecta a los pedidos en curso.
      security:
        - oauth2: ['merchant:write']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [state]
              properties:
                state:
                  type: string
                  enum: [OPEN, CLOSED]
                reason:
                  type: string
                  maxLength: 140
                  example: Alta demanda en cocina
      responses:
        '200':
          description: Estado actualizado.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MerchantStatus'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /merchants/{merchantId}/opening-hours:
    get:
      tags: [Tiendas]
      operationId: getOpeningHours
      summary: Horarios de atención
      security:
        - oauth2: ['merchant:read']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
      responses:
        '200':
          description: Horarios por día de la semana.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OpeningHours'
        '401':
          $ref: '#/components/responses/Unauthorized'
    put:
      tags: [Tiendas]
      operationId: replaceOpeningHours
      summary: Reemplazar horarios de atención
      description: Reemplaza todos los turnos. Un día sin turnos se considera cerrado.
      security:
        - oauth2: ['merchant:write']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OpeningHours'
      responses:
        '200':
          description: Horarios guardados.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OpeningHours'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /merchants/{merchantId}/categories:
    get:
      tags: [Catálogo]
      operationId: listCategories
      summary: Listar categorías
      security:
        - oauth2: ['catalog:read']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
      responses:
        '200':
          description: Categorías del menú.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Category'
        '401':
          $ref: '#/components/responses/Unauthorized'
    post:
      tags: [Catálogo]
      operationId: createCategory
      summary: Crear categoría
      security:
        - oauth2: ['catalog:write']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CategoryInput'
      responses:
        '201':
          description: Categoría creada.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Category'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /merchants/{merchantId}/categories/{categoryId}:
    put:
      tags: [Catálogo]
      operationId: updateCategory
      summary: Actualizar categoría
      security:
        - oauth2: ['catalog:write']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
        - $ref: '#/components/parameters/CategoryId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CategoryInput'
      responses:
        '200':
          description: Categoría actualizada.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Category'
        '404':
          $ref: '#/components/responses/NotFound'
    delete:
      tags: [Catálogo]
      operationId: deleteCategory
      summary: Eliminar categoría
      description: Solo se puede eliminar una categoría sin productos.
      security:
        - oauth2: ['catalog:write']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
        - $ref: '#/components/parameters/CategoryId'
      responses:
        '204':
          description: Categoría eliminada.
        '409':
          $ref: '#/components/responses/Conflict'

  /merchants/{merchantId}/items:
    get:
      tags: [Catálogo]
      operationId: listItems
      summary: Listar productos
      security:
        - oauth2: ['catalog:read']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
        - name: categoryId
          in: query
          schema:
            type: string
        - name: externalCode
          in: query
          description: Busca el producto por el código de su PDV.
          schema:
            type: string
        - $ref: '#/components/parameters/Page'
        - $ref: '#/components/parameters/Size'
      responses:
        '200':
          description: Lista paginada de productos.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Pagination'
                  - type: object
                    properties:
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/Item'
        '401':
          $ref: '#/components/responses/Unauthorized'
    post:
      tags: [Catálogo]
      operationId: createItem
      summary: Crear producto
      security:
        - oauth2: ['catalog:write']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ItemInput'
      responses:
        '201':
          description: Producto creado.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Item'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /merchants/{merchantId}/items/{itemId}:
    get:
      tags: [Catálogo]
      operationId: getItem
      summary: Detalle de un producto
      security:
        - oauth2: ['catalog:read']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
        - $ref: '#/components/parameters/ItemId'
      responses:
        '200':
          description: Producto.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Item'
        '404':
          $ref: '#/components/responses/NotFound'
    put:
      tags: [Catálogo]
      operationId: updateItem
      summary: Actualizar producto
      security:
        - oauth2: ['catalog:write']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
        - $ref: '#/components/parameters/ItemId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ItemInput'
      responses:
        '200':
          description: Producto actualizado.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Item'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
    delete:
      tags: [Catálogo]
      operationId: deleteItem
      summary: Eliminar producto
      security:
        - oauth2: ['catalog:write']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
        - $ref: '#/components/parameters/ItemId'
      responses:
        '204':
          description: Producto eliminado.
        '404':
          $ref: '#/components/responses/NotFound'

  /merchants/{merchantId}/items/{itemId}/availability:
    patch:
      tags: [Catálogo]
      operationId: updateItemAvailability
      summary: Pausar o reactivar un producto
      description: Úselo cuando un producto se queda sin stock. El cambio es inmediato en la app.
      security:
        - oauth2: ['catalog:write']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
        - $ref: '#/components/parameters/ItemId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [available]
              properties:
                available:
                  type: boolean
                  example: false
      responses:
        '200':
          description: Disponibilidad actualizada.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Item'
        '401':
          $ref: '#/components/responses/Unauthorized'

  /merchants/{merchantId}/items/{itemId}/price:
    patch:
      tags: [Catálogo]
      operationId: updateItemPrice
      summary: Actualizar precio
      security:
        - oauth2: ['catalog:write']
      parameters:
        - $ref: '#/components/parameters/MerchantId'
        - $ref: '#/components/parameters/ItemId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [price]
              properties:
                price:
                  $ref: '#/components/schemas/Money'
                originalPrice:
                  description: Precio tachado para mostrar una promoción. Omitir si no hay descuento.
                  $ref: '#/components/schemas/Money'
      responses:
        '200':
          description: Precio actualizado.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Item'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /orders/{orderId}:
    get:
      tags: [Pedidos]
      operationId: getOrder
      summary: Detalle del pedido
      description: Consulte el detalle completo después de recibir el evento `ORDER_PLACED`.
      security:
        - oauth2: ['orders:read']
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '200':
          description: Pedido.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Order'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  /orders/{orderId}/confirm:
    post:
      tags: [Pedidos]
      operationId: confirmOrder
      summary: Confirmar pedido
      description: "`PLACED` → `CONFIRMED`. La tienda acepta el pedido."
      security:
        - oauth2: ['orders:write']
      parameters:
        - $ref: '#/components/parameters/OrderId'
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                preparationTimeMinutes:
                  type: integer
                  minimum: 1
                  maximum: 180
                  description: Tiempo estimado de preparación. Si se omite, se usa el configurado en la tienda.
                  example: 25
      responses:
        '202':
          $ref: '#/components/responses/Accepted'
        '409':
          $ref: '#/components/responses/InvalidTransition'

  /orders/{orderId}/start-preparation:
    post:
      tags: [Pedidos]
      operationId: startPreparation
      summary: Iniciar preparación
      description: "`CONFIRMED` → `PREPARING`."
      security:
        - oauth2: ['orders:write']
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '202':
          $ref: '#/components/responses/Accepted'
        '409':
          $ref: '#/components/responses/InvalidTransition'

  /orders/{orderId}/ready:
    post:
      tags: [Pedidos]
      operationId: readyForPickup
      summary: Listo para retirar
      description: "`PREPARING` → `READY_FOR_PICKUP`. Avisa al repartidor o al cliente (retiro en local)."
      security:
        - oauth2: ['orders:write']
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '202':
          $ref: '#/components/responses/Accepted'
        '409':
          $ref: '#/components/responses/InvalidTransition'

  /orders/{orderId}/dispatch:
    post:
      tags: [Pedidos]
      operationId: dispatchOrder
      summary: Despachar (entrega propia)
      description: |
        `READY_FOR_PICKUP` → `DISPATCHED`. Solo para pedidos con `delivery.deliveredBy = MERCHANT`.
        Cuando entrega un repartidor KaruGO, este estado lo informa el propio repartidor.
      security:
        - oauth2: ['orders:write']
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '202':
          $ref: '#/components/responses/Accepted'
        '409':
          $ref: '#/components/responses/InvalidTransition'

  /orders/{orderId}/conclude:
    post:
      tags: [Pedidos]
      operationId: concludeOrder
      summary: Concluir (entrega propia o retiro)
      description: |
        `DISPATCHED` o `READY_FOR_PICKUP` → `CONCLUDED`. Para entrega propia (`MERCHANT`) o retiro en local (`TAKEOUT`).
      security:
        - oauth2: ['orders:write']
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '202':
          $ref: '#/components/responses/Accepted'
        '409':
          $ref: '#/components/responses/InvalidTransition'

  /orders/{orderId}/cancellation-reasons:
    get:
      tags: [Pedidos]
      operationId: listCancellationReasons
      summary: Motivos de cancelación
      description: Motivos válidos para cancelar este pedido en su estado actual.
      security:
        - oauth2: ['orders:read']
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '200':
          description: Motivos disponibles.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/CancellationReason'
        '401':
          $ref: '#/components/responses/Unauthorized'

  /orders/{orderId}/cancel:
    post:
      tags: [Pedidos]
      operationId: cancelOrder
      summary: Cancelar pedido
      description: Cancela el pedido con uno de los motivos de `GET /orders/{orderId}/cancellation-reasons`.
      security:
        - oauth2: ['orders:write']
      parameters:
        - $ref: '#/components/parameters/OrderId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reasonCode]
              properties:
                reasonCode:
                  type: string
                  example: ITEM_UNAVAILABLE
                details:
                  type: string
                  maxLength: 255
                  description: Obligatorio cuando `reasonCode` es `OTHER`.
                  example: Sin stock de empanadas de carne
      responses:
        '202':
          $ref: '#/components/responses/Accepted'
        '409':
          $ref: '#/components/responses/InvalidTransition'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /events/polling:
    get:
      tags: [Eventos]
      operationId: pollEvents
      summary: Consultar eventos (polling)
      description: |
        Devuelve hasta 100 eventos pendientes de confirmación, del más antiguo al más reciente.
        Consulte cada **30 segundos** y confirme con `POST /events/acknowledgment`.
        Responde `204` cuando no hay eventos.
      security:
        - oauth2: ['events:read']
      parameters:
        - name: merchantId
          in: query
          description: Filtra por una o más tiendas (separadas por coma). Por defecto, todas las autorizadas.
          schema:
            type: string
          example: '1024,1031'
        - name: types
          in: query
          description: Filtra por tipos de evento (separados por coma).
          schema:
            type: string
          example: ORDER_PLACED,ORDER_CANCELLED
      responses:
        '200':
          description: Eventos pendientes.
          content:
            application/json:
              schema:
                type: array
                maxItems: 100
                items:
                  $ref: '#/components/schemas/Event'
        '204':
          description: No hay eventos pendientes.
        '429':
          $ref: '#/components/responses/TooManyRequests'

  /events/acknowledgment:
    post:
      tags: [Eventos]
      operationId: acknowledgeEvents
      summary: Confirmar eventos
      description: |
        Marca los eventos como procesados para que no se vuelvan a entregar.
        Los eventos sin confirmar se reenvían durante 24 horas.
      security:
        - oauth2: ['events:read']
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: array
              minItems: 1
              maxItems: 100
              items:
                type: object
                required: [id]
                properties:
                  id:
                    type: string
                    format: uuid
            example:
              - id: 3f0e9c1a-7b2d-4d7e-9f57-2c9a8f1b6e40
      responses:
        '202':
          description: Eventos confirmados.
        '401':
          $ref: '#/components/responses/Unauthorized'

  /shipping/quotes:
    post:
      tags: [Envíos]
      operationId: createShippingQuote
      summary: Cotizar envío
      description: Calcula tarifa y tiempos estimados. La cotización vale 10 minutos.
      security:
        - oauth2: ['shipping:write']
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ShippingQuoteRequest'
      responses:
        '201':
          description: Cotización creada.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ShippingQuote'
        '422':
          description: Dirección fuera del área de cobertura o datos inválidos.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error:
                  code: out_of_coverage
                  message: La dirección de entrega está fuera del área de cobertura.
                  traceId: a81d0c4f92e34b11

  /shipping/deliveries:
    post:
      tags: [Envíos]
      operationId: createDelivery
      summary: Crear envío
      description: Confirma una cotización vigente y solicita un repartidor.
      security:
        - oauth2: ['shipping:write']
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeliveryRequest'
      responses:
        '201':
          description: Envío creado.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Delivery'
        '410':
          description: La cotización expiró.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /shipping/deliveries/{deliveryId}:
    get:
      tags: [Envíos]
      operationId: getDelivery
      summary: Consultar envío
      security:
        - oauth2: ['shipping:read']
      parameters:
        - $ref: '#/components/parameters/DeliveryId'
      responses:
        '200':
          description: Envío.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Delivery'
        '404':
          $ref: '#/components/responses/NotFound'

  /shipping/deliveries/{deliveryId}/cancel:
    post:
      tags: [Envíos]
      operationId: cancelDelivery
      summary: Cancelar envío
      description: Solo es posible antes de que el repartidor retire el paquete (`PICKED_UP`).
      security:
        - oauth2: ['shipping:write']
      parameters:
        - $ref: '#/components/parameters/DeliveryId'
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                reason:
                  type: string
                  maxLength: 255
      responses:
        '202':
          $ref: '#/components/responses/Accepted'
        '409':
          $ref: '#/components/responses/InvalidTransition'

  /sandbox/test-orders:
    post:
      tags: [Sandbox]
      operationId: createTestOrder
      summary: Crear pedido de prueba
      description: Crea un pedido ficticio en una tienda de prueba y emite el evento `ORDER_PLACED`.
      servers:
        - url: https://sandbox.merchant-api.karugo.com.py/v1
          description: Sandbox
      security:
        - oauth2: ['orders:read']
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [merchantId]
              properties:
                merchantId:
                  type: string
                  example: '1024'
                type:
                  type: string
                  enum: [DELIVERY, TAKEOUT]
                  default: DELIVERY
                paymentMethod:
                  type: string
                  enum: [CASH, CARD_ON_DELIVERY, ONLINE]
                  default: CASH
                items:
                  type: array
                  description: Si se omite, se eligen productos al azar del catálogo de prueba.
                  items:
                    type: object
                    required: [itemId, quantity]
                    properties:
                      itemId:
                        type: string
                        example: '5531'
                      quantity:
                        type: integer
                        minimum: 1
                        example: 2
      responses:
        '201':
          description: Pedido de prueba creado.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Order'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /sandbox/test-orders/{orderId}/customer-cancellation:
    post:
      tags: [Sandbox]
      operationId: simulateCustomerCancellation
      summary: Simular cancelación del cliente
      description: Cancela el pedido como si lo hubiera hecho el cliente y emite `ORDER_CANCELLED`.
      servers:
        - url: https://sandbox.merchant-api.karugo.com.py/v1
          description: Sandbox
      security:
        - oauth2: ['orders:read']
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '202':
          $ref: '#/components/responses/Accepted'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          $ref: '#/components/responses/InvalidTransition'

webhooks:
  event:
    post:
      tags: [Eventos]
      operationId: receiveEventWebhook
      summary: Webhook de eventos
      description: |
        KaruGO envía un `POST` a la URL configurada en su aplicación por cada evento.
        Responda `2xx` en menos de 5 segundos; si no, reintentamos con espera exponencial durante 24 horas.

        **Firma:** `X-KaruGO-Signature: sha256=<hex>` = HMAC-SHA256 de `"{X-KaruGO-Timestamp}.{cuerpo}"`
        usando el *webhook secret* de su aplicación. Rechace mensajes con más de 5 minutos.
      security: []
      parameters:
        - name: X-KaruGO-Signature
          in: header
          required: true
          schema:
            type: string
          example: sha256=5d5b09f6dcb2d53a5fffc60c4ac0d55fabdf556069d6631545f42aa6e3500f2e
        - name: X-KaruGO-Timestamp
          in: header
          required: true
          description: Segundos Unix del momento del envío.
          schema:
            type: integer
          example: 1764072000
        - name: X-KaruGO-Event-Id
          in: header
          required: true
          schema:
            type: string
            format: uuid
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Event'
      responses:
        '200':
          description: Evento recibido.

components:
  securitySchemes:
    oauth2:
      type: oauth2
      description: "OAuth 2.0 client credentials. Envíe el token en `Authorization: Bearer <token>`."
      flows:
        clientCredentials:
          tokenUrl: https://merchant-api.karugo.com.py/v1/oauth/token
          scopes:
            merchant:read: Leer tiendas, estado y horarios
            merchant:write: Abrir/cerrar tiendas y editar horarios
            catalog:read: Leer el catálogo
            catalog:write: Editar categorías, productos, precios y disponibilidad
            orders:read: Leer pedidos
            orders:write: Cambiar el estado de los pedidos
            events:read: Recibir y confirmar eventos
            shipping:read: Consultar envíos
            shipping:write: Cotizar, crear y cancelar envíos

  parameters:
    MerchantId:
      name: merchantId
      in: path
      required: true
      schema:
        type: string
      example: '1024'
    CategoryId:
      name: categoryId
      in: path
      required: true
      schema:
        type: string
    ItemId:
      name: itemId
      in: path
      required: true
      schema:
        type: string
    OrderId:
      name: orderId
      in: path
      required: true
      schema:
        type: string
      example: '100245'
    DeliveryId:
      name: deliveryId
      in: path
      required: true
      schema:
        type: string
      example: dlv_8KQ2M4
    Page:
      name: page
      in: query
      schema:
        type: integer
        minimum: 1
        default: 1
    Size:
      name: size
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 50
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      description: Clave única (por ejemplo, un UUID) para reintentar la creación sin duplicar recursos. Válida por 24 horas.
      schema:
        type: string
        maxLength: 64

  responses:
    Accepted:
      description: Solicitud aceptada. El cambio de estado se confirma con un evento.
    BadRequest:
      description: Solicitud mal formada.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Unauthorized:
      description: Token ausente, inválido o vencido.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: unauthorized
              message: El token de acceso no es válido o venció.
              traceId: 0b6e1f7d2c9a4e35
    NotFound:
      description: Recurso inexistente o no autorizado para su aplicación.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Conflict:
      description: Conflicto con el estado actual (por ejemplo, `externalCode` duplicado).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    InvalidTransition:
      description: La acción no es válida en el estado actual del pedido o envío.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: invalid_status_transition
              message: No es posible pasar de CONCLUDED a PREPARING.
              traceId: 92c4ad01f7e64b2a
    UnprocessableEntity:
      description: Error de validación.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: validation_error
              message: Algunos campos no son válidos.
              details:
                - field: price.value
                  message: Debe ser un entero mayor o igual a 0.
              traceId: 4a7e0d9c13b84f62
    TooManyRequests:
      description: Límite de uso superado. Espere `Retry-After` segundos.
      headers:
        Retry-After:
          schema:
            type: integer
        X-RateLimit-Limit:
          schema:
            type: integer
        X-RateLimit-Remaining:
          schema:
            type: integer
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

  schemas:
    AccessToken:
      type: object
      required: [access_token, token_type, expires_in]
      properties:
        access_token:
          type: string
          example: eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9…
        token_type:
          type: string
          enum: [Bearer]
        expires_in:
          type: integer
          description: Segundos hasta el vencimiento.
          example: 21600
        scope:
          type: string
          example: orders:read orders:write events:read

    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message, traceId]
          properties:
            code:
              type: string
              description: Código estable, legible por máquina.
              example: validation_error
            message:
              type: string
              description: Descripción legible para personas. Puede cambiar; no la use en lógica.
            details:
              type: array
              items:
                type: object
                properties:
                  field:
                    type: string
                  message:
                    type: string
            traceId:
              type: string
              description: Identificador para soporte. Inclúyalo al reportar un problema.

    Pagination:
      type: object
      properties:
        page:
          type: integer
          example: 1
        size:
          type: integer
          example: 50
        total:
          type: integer
          example: 2

    Money:
      type: object
      required: [value, currency]
      properties:
        value:
          type: integer
          description: Monto en la unidad mínima de la moneda (guaraníes enteros).
          example: 45000
        currency:
          type: string
          enum: [PYG]
          example: PYG

    GeoPoint:
      type: object
      required: [latitude, longitude]
      properties:
        latitude:
          type: number
          format: double
          example: -25.2865
        longitude:
          type: number
          format: double
          example: -57.6470

    Address:
      type: object
      properties:
        formattedAddress:
          type: string
          example: Av. Mariscal López 1234, Asunción
        reference:
          type: string
          example: Portón negro, frente a la farmacia
        city:
          type: string
          example: Asunción
        location:
          $ref: '#/components/schemas/GeoPoint'

    MerchantSummary:
      type: object
      properties:
        id:
          type: string
          example: '1024'
        name:
          type: string
          example: Lomitería Don Pepe
        externalCode:
          type: [string, 'null']
          example: SUC-CENTRO

    Merchant:
      allOf:
        - $ref: '#/components/schemas/MerchantSummary'
        - type: object
          properties:
            phone:
              type: string
              example: '+595981000000'
            address:
              $ref: '#/components/schemas/Address'
            zoneId:
              type: string
              example: '3'
            deliveredBy:
              type: string
              enum: [KARUGO, MERCHANT]
              description: Quién entrega los pedidos de esta tienda por defecto.
            averagePreparationTimeMinutes:
              type: integer
              example: 25
            minimumOrder:
              $ref: '#/components/schemas/Money'

    MerchantStatus:
      type: object
      properties:
        state:
          type: string
          enum: [OPEN, CLOSED]
        reason:
          type: string
          enum: [OPEN, OUTSIDE_OPENING_HOURS, CLOSED_BY_MERCHANT, CLOSED_BY_KARUGO]
          description: Motivo del estado actual.
        nextOpeningAt:
          type: [string, 'null']
          format: date-time
        updatedAt:
          type: string
          format: date-time

    OpeningHours:
      type: object
      required: [shifts]
      properties:
        timezone:
          type: string
          example: America/Asuncion
          readOnly: true
        shifts:
          type: array
          items:
            type: object
            required: [dayOfWeek, start, end]
            properties:
              dayOfWeek:
                type: string
                enum: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]
              start:
                type: string
                pattern: '^([01]\d|2[0-3]):[0-5]\d$'
                example: '11:00'
              end:
                type: string
                pattern: '^([01]\d|2[0-3]):[0-5]\d$'
                example: '23:30'

    CategoryInput:
      type: object
      required: [name]
      properties:
        name:
          type: string
          maxLength: 100
          example: Lomitos
        externalCode:
          type: string
          maxLength: 64
          example: CAT-LOMITOS
        position:
          type: integer
          description: Orden de la categoría en el menú (0 = primera).
          example: 0

    Category:
      allOf:
        - type: object
          properties:
            id:
              type: string
              example: '87'
        - $ref: '#/components/schemas/CategoryInput'

    OptionGroup:
      type: object
      required: [name, minSelections, maxSelections, options]
      description: Grupo de opciones del producto (por ejemplo, "Tamaño" o "Adicionales").
      properties:
        id:
          type: string
          readOnly: true
        name:
          type: string
          example: Adicionales
        externalCode:
          type: string
        minSelections:
          type: integer
          minimum: 0
          example: 0
        maxSelections:
          type: integer
          minimum: 1
          example: 3
        options:
          type: array
          items:
            type: object
            required: [name, price]
            properties:
              id:
                type: string
                readOnly: true
              name:
                type: string
                example: Huevo frito
              externalCode:
                type: string
                example: ADD-HUEVO
              price:
                $ref: '#/components/schemas/Money'
              available:
                type: boolean
                default: true

    ItemInput:
      type: object
      required: [name, categoryId, price]
      properties:
        name:
          type: string
          maxLength: 150
          example: Lomito completo
        description:
          type: string
          maxLength: 1000
          example: Lomito con jamón, queso, huevo, lechuga y tomate.
        categoryId:
          type: string
          example: '87'
        externalCode:
          type: string
          maxLength: 64
          description: Código del producto en su PDV. Único por tienda.
          example: PLU-1001
        price:
          $ref: '#/components/schemas/Money'
        originalPrice:
          $ref: '#/components/schemas/Money'
        imageUrl:
          type: string
          format: uri
          description: URL pública (JPG o PNG, mínimo 600×600 px). KaruGO descarga y guarda una copia.
        available:
          type: boolean
          default: true
        optionGroups:
          type: array
          items:
            $ref: '#/components/schemas/OptionGroup'

    Item:
      allOf:
        - type: object
          properties:
            id:
              type: string
              example: '5531'
            updatedAt:
              type: string
              format: date-time
        - $ref: '#/components/schemas/ItemInput'

    OrderStatus:
      type: string
      description: |
        | Estado | Significado |
        |---|---|
        | `PLACED` | Pedido realizado, esperando confirmación de la tienda. |
        | `CONFIRMED` | La tienda aceptó el pedido. |
        | `PREPARING` | En preparación. |
        | `READY_FOR_PICKUP` | Listo para que lo retire el repartidor o el cliente. |
        | `DISPATCHED` | En camino al cliente. |
        | `CONCLUDED` | Entregado. |
        | `CANCELLED` | Cancelado. |
      enum: [PLACED, CONFIRMED, PREPARING, READY_FOR_PICKUP, DISPATCHED, CONCLUDED, CANCELLED]

    OrderItem:
      type: object
      properties:
        id:
          type: string
          example: '5531'
        externalCode:
          type: [string, 'null']
          example: PLU-1001
        name:
          type: string
          example: Lomito completo
        quantity:
          type: integer
          example: 2
        unitPrice:
          $ref: '#/components/schemas/Money'
        totalPrice:
          $ref: '#/components/schemas/Money'
        notes:
          type: [string, 'null']
          example: Sin tomate
        options:
          type: array
          items:
            type: object
            properties:
              groupName:
                type: string
                example: Adicionales
              name:
                type: string
                example: Huevo frito
              externalCode:
                type: [string, 'null']
                example: ADD-HUEVO
              quantity:
                type: integer
                example: 1
              unitPrice:
                $ref: '#/components/schemas/Money'

    Order:
      type: object
      properties:
        id:
          type: string
          example: '100245'
        displayId:
          type: string
          description: Número corto para mostrar en cocina y al repartidor.
          example: '0245'
        merchant:
          $ref: '#/components/schemas/MerchantSummary'
        status:
          $ref: '#/components/schemas/OrderStatus'
        type:
          type: string
          enum: [DELIVERY, TAKEOUT, DINE_IN]
        createdAt:
          type: string
          format: date-time
          example: '2026-11-25T15:04:05Z'
        scheduledFor:
          type: [string, 'null']
          format: date-time
          description: Si el pedido es programado, fecha y hora de entrega solicitada.
        preparationDeadline:
          type: [string, 'null']
          format: date-time
        customer:
          type: object
          properties:
            name:
              type: string
              example: María G.
            phone:
              type: string
              description: Teléfono de contacto (puede ser un número enmascarado).
              example: '+595981000001'
            documentNumber:
              type: [string, 'null']
              description: RUC o CI si el cliente pidió factura.
        delivery:
          type: [object, 'null']
          properties:
            deliveredBy:
              type: string
              enum: [KARUGO, MERCHANT]
            address:
              $ref: '#/components/schemas/Address'
            estimatedDeliveryAt:
              type: string
              format: date-time
            driver:
              type: [object, 'null']
              properties:
                name:
                  type: string
                  example: Juan P.
                phone:
                  type: string
                vehicle:
                  type: string
                  example: Moto
        items:
          type: array
          items:
            $ref: '#/components/schemas/OrderItem'
        totals:
          type: object
          properties:
            subtotal:
              $ref: '#/components/schemas/Money'
            deliveryFee:
              $ref: '#/components/schemas/Money'
            discount:
              $ref: '#/components/schemas/Money'
            tax:
              $ref: '#/components/schemas/Money'
            total:
              $ref: '#/components/schemas/Money'
        payment:
          type: object
          properties:
            method:
              type: string
              enum: [CASH, CARD_ON_DELIVERY, ONLINE, WALLET]
            prepaid:
              type: boolean
              description: true si el cliente ya pagó en la app.
            changeFor:
              $ref: '#/components/schemas/Money'
        notes:
          type: [string, 'null']
          example: Tocar timbre
        cancellation:
          type: [object, 'null']
          properties:
            reasonCode:
              type: string
            reason:
              type: string
            cancelledBy:
              type: string
              enum: [MERCHANT, CUSTOMER, KARUGO]
            cancelledAt:
              type: string
              format: date-time

    CancellationReason:
      type: object
      properties:
        code:
          type: string
          example: ITEM_UNAVAILABLE
        description:
          type: string
          example: Producto sin stock

    Event:
      type: object
      required: [id, type, createdAt]
      properties:
        id:
          type: string
          format: uuid
          example: 3f0e9c1a-7b2d-4d7e-9f57-2c9a8f1b6e40
        type:
          type: string
          enum:
            - ORDER_PLACED
            - ORDER_CONFIRMED
            - ORDER_PREPARING
            - ORDER_READY_FOR_PICKUP
            - ORDER_DRIVER_ASSIGNED
            - ORDER_DISPATCHED
            - ORDER_CONCLUDED
            - ORDER_CANCELLED
            - DELIVERY_DRIVER_ASSIGNED
            - DELIVERY_PICKED_UP
            - DELIVERY_DELIVERED
            - DELIVERY_CANCELLED
            - DELIVERY_FAILED
          example: ORDER_PLACED
        merchantId:
          type: string
          example: '1024'
        orderId:
          type: [string, 'null']
          example: '100245'
        deliveryId:
          type: [string, 'null']
        createdAt:
          type: string
          format: date-time
          example: '2026-11-25T15:04:05Z'
        metadata:
          type: object
          additionalProperties: true
          description: Datos adicionales según el tipo (por ejemplo, el motivo de una cancelación).

    ShippingQuoteRequest:
      type: object
      required: [merchantId, dropoff]
      properties:
        merchantId:
          type: string
          description: Tienda de origen. El retiro se hace en su dirección registrada.
          example: '1024'
        dropoff:
          $ref: '#/components/schemas/Address'
        orderValue:
          $ref: '#/components/schemas/Money'

    ShippingQuote:
      type: object
      properties:
        id:
          type: string
          example: qt_3Hc9Zp
        fee:
          $ref: '#/components/schemas/Money'
        distanceMeters:
          type: integer
          example: 4200
        estimatedPickupMinutes:
          type: integer
          example: 12
        estimatedDeliveryMinutes:
          type: integer
          example: 35
        expiresAt:
          type: string
          format: date-time

    DeliveryRequest:
      type: object
      required: [quoteId, customer]
      properties:
        quoteId:
          type: string
          example: qt_3Hc9Zp
        externalReference:
          type: string
          description: Identificador del pedido en su sistema.
          example: VTA-2026-000981
        customer:
          type: object
          required: [name, phone]
          properties:
            name:
              type: string
              example: Carlos R.
            phone:
              type: string
              example: '+595971000002'
        dropoffInstructions:
          type: string
          maxLength: 255
          example: Dejar en portería
        packageDescription:
          type: string
          maxLength: 255
          example: 2 bolsas medianas
        cashOnDelivery:
          description: Monto que el repartidor debe cobrar al entregar. Omitir si ya está pago.
          $ref: '#/components/schemas/Money'

    Delivery:
      type: object
      properties:
        id:
          type: string
          example: dlv_8KQ2M4
        status:
          type: string
          enum: [REQUESTED, DRIVER_ASSIGNED, PICKED_UP, DELIVERED, CANCELLED, FAILED]
        externalReference:
          type: string
        fee:
          $ref: '#/components/schemas/Money'
        trackingUrl:
          type: string
          format: uri
          example: https://track.karugo.com.py/dlv_8KQ2M4
        driver:
          type: [object, 'null']
          properties:
            name:
              type: string
            phone:
              type: string
            location:
              allOf:
                - $ref: '#/components/schemas/GeoPoint'
                - type: object
                  properties:
                    updatedAt:
                      type: string
                      format: date-time
        createdAt:
          type: string
          format: date-time
        estimatedDeliveryAt:
          type: string
          format: date-time
