openapi: 3.1.0
info:
  title: Hego Buyer API
  version: 1.0.0
  description: >
    La especificación OpenAPI (anteriormente Swagger) es un estándar de la industria para documentar APIs REST.
    Puedes usar este archivo para generar automáticamente código cliente en tu lenguaje favorito (Python, JS, Go, etc.),
    o importarlo en herramientas como Postman o Insomnia para probar los endpoints inmediatamente.

    Esta API permite a clientes B2B consultar el catálogo, realizar compras con la billetera Hego,
    y suscribirse a webhooks de eventos en tiempo real.
servers:
  - url: https://api.hegodigitaldev.com/api/v1/buyer
    description: HegoMarket Production Server
components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: "Tu clave secreta de API. Alternativamente, puedes usar `Authorization: Bearer <tu_clave>`."
  schemas:
    ErrorResponse:
      type: object
      properties:
        error:
          type: string
          example: "INSUFFICIENT_FUNDS"
        message:
          type: string
          example: "No tienes saldo suficiente en tu billetera."
        requestId:
          type: string
          example: "req_8f73b2a"
    OrderPayload:
      type: object
      properties:
        orderId:
          type: integer
          example: 45012
        status:
          type: string
          enum: [processing, pending_delivery, completed, failed, refunded]
          example: "completed"
        productId:
          type: integer
          example: 102
        quantity:
          type: integer
          example: 1
        totalPriceUsdt:
          type: number
          example: 12.50
        createdAt:
          type: string
          format: date-time
        delivery:
          type: object
          description: "Solo presente si el status es 'completed'"
          properties:
            items:
              type: array
              description: "Para productos estándar (credenciales, links, pines)"
              items:
                type: string
              example: ["email:password", "https://link.com/redeem"]
            downloadUrl:
              type: string
              description: "Para productos tipo archivo"
              example: "https://api.hegodigitaldev.com/api/v1/buyer/orders/45012/download"
paths:
  /health:
    get:
      summary: Health Check
      description: Verifica si la API está operativa. No requiere autenticación.
      responses:
        '200':
          description: API Operativa
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    example: "ok"
                  version:
                    type: string
                    example: "1.0.0"
  /products:
    get:
      summary: Consultar Catálogo
      description: Obtiene la lista completa de productos activos, incluyendo precios y descripciones.
      security:
        - ApiKeyAuth: []
      responses:
        '200':
          description: Catálogo devuelto exitosamente
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id:
                      type: integer
                      example: 102
                    name:
                      type: string
                      example: "Netflix 1 Pantalla (30 Días)"
                    priceUsdt:
                      type: number
                      example: 3.50
                    type:
                      type: string
                      enum: [standard, file, manual]
                    active:
                      type: boolean
  /balance:
    get:
      summary: Consultar Saldo
      description: Obtiene el saldo USDT disponible en tu billetera.
      security:
        - ApiKeyAuth: []
      responses:
        '200':
          description: Saldo devuelto exitosamente
          content:
            application/json:
              schema:
                type: object
                properties:
                  balanceUsdt:
                    type: number
                    example: 150.25
  /orders:
    post:
      summary: Crear Compra
      description: |
        Crea una nueva orden de compra. Descuenta el saldo y reserva el stock.
        Requiere el header `Idempotency-Key` para evitar cargos duplicados si hay fallos de red.
      security:
        - ApiKeyAuth: []
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          schema:
            type: string
            example: "idem_93j2kf092j3f"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [productId, quantity, expectedPriceUsdt]
              properties:
                productId:
                  type: integer
                  example: 102
                quantity:
                  type: integer
                  example: 1
                expectedPriceUsdt:
                  type: number
                  example: 3.50
                  description: "Precio unitario esperado. Evita compras erróneas si el precio cambia."
                recipientUsername:
                  type: string
                  example: "@compradorFinal"
                  description: "Obligatorio para productos de recarga directa."
      responses:
        '200':
          description: Orden creada exitosamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderPayload'
        '400':
          description: Bad Request (Faltan campos o mal formados)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '409':
          description: Conflicto (Precio cambió o Idempotency-Key en uso)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{id}:
    get:
      summary: Consultar Orden
      description: |
        Obtiene el estado de una orden previa. 
        Si el producto era asíncrono y se completó, aquí recibirás los items de entrega.
      security:
        - ApiKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: Estado de la orden
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderPayload'
  /orders/{id}/download:
    get:
      summary: Descargar Archivo (File Products)
      description: Descarga el archivo original asociado a la orden (solo válido para productos tipo `file`).
      security:
        - ApiKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: Archivo Binario
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
  /webhook:
    get:
      summary: Consultar Configuración Webhook
      description: Obtiene la configuración actual de notificaciones.
      security:
        - ApiKeyAuth: []
      responses:
        '200':
          description: Configuración actual
          content:
            application/json:
              schema:
                type: object
                properties:
                  url:
                    type: string
                    example: "https://tudominio.com/webhook"
                  events:
                    type: array
                    items:
                      type: string
                    example: ["order.completed", "stock.changed", "catalog.updated"]
                  balanceThresholdUsdt:
                    type: number
                    example: 20.00
    post:
      summary: Configurar Webhook
      description: Establece o actualiza la URL y los eventos a los que deseas suscribirte.
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url, events]
              properties:
                url:
                  type: string
                  example: "https://tudominio.com/webhook"
                events:
                  type: array
                  items:
                    type: string
                  example: ["order.completed", "stock.changed"]
                balanceThresholdUsdt:
                  type: number
                  example: 10.00
      responses:
        '200':
          description: Configuración guardada
          content:
            application/json:
              schema:
                type: object
                properties:
                  secret:
                    type: string
                    example: "whsec_live_a1b2c3d4..."
                    description: "Secreto usado para validar la firma HMAC-SHA256 (X-Hego-Signature) de los webhooks entrantes."
    delete:
      summary: Eliminar Webhook
      description: Desactiva todas las notificaciones push.
      security:
        - ApiKeyAuth: []
      responses:
        '200':
          description: Webhooks desactivados
