openapi: 3.0.3
info:
  title: BrainPrices Marketplace API
  description: |
    API REST completa para integración con el marketplace BrainPrices.
    
    **Características:**
    - Autenticación JWT
    - Soporte multi-idioma
    - Paginación en todas las listas
    - Rate limiting
    - Webhooks para integraciones externas
    
    **Base URL:** `https://www.brainprices.com/api/v1`
  version: 1.0.0
  contact:
    name: BrainPrices Support
    url: https://www.brainprices.com/contacto
  license:
    name: Proprietary

servers:
  - url: https://www.brainprices.com/api/v1
    description: Servidor de Producción
  - url: http://localhost/api/v1
    description: Servidor de Desarrollo

tags:
  - name: Autenticación
    description: Endpoints de autenticación y gestión de tokens
  - name: Productos
    description: Gestión de productos
  - name: Categorías
    description: Gestión de categorías
  - name: Pedidos
    description: Gestión de pedidos
  - name: Carrito
    description: Gestión del carrito de compras
  - name: Clientes
    description: Gestión de clientes
  - name: Asociados
    description: Gestión de vendedores asociados
  - name: Pagos
    description: Procesamiento de pagos
  - name: Envíos
    description: Métodos de envío y tracking
  - name: Cupones
    description: Cupones de descuento
  - name: Reseñas
    description: Reseñas y valoraciones
  - name: Atributos
    description: Atributos de productos
  - name: Fabricantes
    description: Gestión de fabricantes
  - name: Sincronización
    description: Sincronización con plataformas externas
  - name: Webhooks
    description: Webhooks para integraciones
  - name: Configuración
    description: Configuración del sistema

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: Token JWT obtenido del endpoint de login

  schemas:
    Error:
      type: object
      properties:
        success:
          type: boolean
          example: false
        message:
          type: string
          example: "Error en la operación"
        errors:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
        code:
          type: string
          example: "VALIDATION_ERROR"

    Pagination:
      type: object
      properties:
        current_page:
          type: integer
          example: 1
        per_page:
          type: integer
          example: 20
        total:
          type: integer
          example: 500
        total_pages:
          type: integer
          example: 25
        has_more:
          type: boolean
          example: true
        next_page:
          type: integer
          nullable: true
          example: 2
        prev_page:
          type: integer
          nullable: true
          example: null

    Product:
      type: object
      properties:
        id:
          type: integer
          example: 123
        uuid:
          type: string
          format: uuid
          example: "550e8400-e29b-41d4-a716-446655440000"
        name:
          type: string
          example: "Vino Rioja Reserva 2020"
        slug:
          type: string
          example: "vino-rioja-reserva-2020"
        description:
          type: string
          example: "<p>Excelente vino de Rioja...</p>"
        short_description:
          type: string
          example: "Vino tinto reserva de la DOC Rioja"
        sku:
          type: string
          example: "VIN-RIOJA-2020"
        ean13:
          type: string
          example: "1234567890123"
        price:
          type: number
          format: float
          example: 24.99
        compare_price:
          type: number
          format: float
          nullable: true
          example: 34.99
        stock_quantity:
          type: integer
          example: 50
        category_id:
          type: integer
          example: 5
        category_name:
          type: string
          example: "Vinos"
        associate_id:
          type: integer
          example: 10
        associate_name:
          type: string
          example: "Bodega López"
        primary_image:
          type: string
          example: "/uploads/products/vino-rioja.jpg"
        status:
          type: string
          enum: [active, inactive]
          example: "active"
        featured:
          type: boolean
          example: true
        created_at:
          type: string
          format: date-time
          example: "2024-01-15T10:30:00Z"

    Category:
      type: object
      properties:
        id:
          type: integer
          example: 1
        name:
          type: string
          example: "Vinos"
        slug:
          type: string
          example: "vinos"
        description:
          type: string
          example: "Amplia selección de vinos"
        parent_id:
          type: integer
          nullable: true
          example: null
        image:
          type: string
          nullable: true
          example: "/uploads/categories/vinos.jpg"
        products_count:
          type: integer
          example: 245
        status:
          type: string
          enum: [active, inactive]
          example: "active"

    Order:
      type: object
      properties:
        id:
          type: integer
          example: 1001
        order_number:
          type: string
          example: "ORD-2024-001001"
        status:
          type: string
          enum: [pending, processing, shipped, delivered, cancelled]
          example: "processing"
        payment_status:
          type: string
          enum: [pending, paid, failed, refunded]
          example: "paid"
        total:
          type: number
          format: float
          example: 125.50
        items_count:
          type: integer
          example: 3
        created_at:
          type: string
          format: date-time

paths:
  /auth/login:
    post:
      tags:
        - Autenticación
      summary: Iniciar sesión
      description: Autenticar usuario y obtener token de acceso
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
                - password
              properties:
                email:
                  type: string
                  format: email
                  example: "user@example.com"
                password:
                  type: string
                  format: password
                  example: "password123"
      responses:
        '200':
          description: Login exitoso
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  token:
                    type: string
                    example: "eyJ0eXAiOiJKV1QiLCJhbGc..."
                  refresh_token:
                    type: string
                  expires_in:
                    type: integer
                    example: 3600
                  user:
                    type: object
        '401':
          description: Credenciales inválidas
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /productos:
    get:
      tags:
        - Productos
      summary: Listar productos
      description: Obtener lista de productos con filtros y paginación
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: per_page
          in: query
          schema:
            type: integer
            default: 20
            maximum: 100
        - name: search
          in: query
          description: Buscar por nombre o SKU
          schema:
            type: string
        - name: category_id
          in: query
          schema:
            type: integer
        - name: status
          in: query
          schema:
            type: string
            enum: [active, inactive]
        - name: featured
          in: query
          schema:
            type: boolean
        - name: on_sale
          in: query
          schema:
            type: boolean
        - name: sort
          in: query
          schema:
            type: string
            enum: [name, price, created_at, sales]
            default: created_at
        - name: order
          in: query
          schema:
            type: string
            enum: [asc, desc]
            default: desc
      responses:
        '200':
          description: Lista de productos
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Product'
                  pagination:
                    $ref: '#/components/schemas/Pagination'
    
    post:
      tags:
        - Productos
      summary: Crear producto
      description: Crear un nuevo producto. Requiere autenticación.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - price
                - sku
                - category_id
              properties:
                name:
                  type: string
                  example: "Aceite de Oliva Virgen Extra"
                description:
                  type: string
                short_description:
                  type: string
                sku:
                  type: string
                  example: "ACE-OLIVA-001"
                price:
                  type: number
                  format: float
                  example: 12.50
                compare_price:
                  type: number
                  format: float
                stock_quantity:
                  type: integer
                  example: 100
                category_id:
                  type: integer
                  example: 3
                status:
                  type: string
                  enum: [active, inactive]
                  default: active
      responses:
        '201':
          description: Producto creado
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
        '401':
          description: No autenticado
        '422':
          description: Validación fallida

  /productos/{id}:
    get:
      tags:
        - Productos
      summary: Obtener producto
      description: Obtener detalles completos de un producto
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: Detalles del producto
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Product'
        '404':
          description: Producto no encontrado

    put:
      tags:
        - Productos
      summary: Actualizar producto
      description: Actualizar producto existente. Requiere autenticación.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                price:
                  type: number
                stock_quantity:
                  type: integer
      responses:
        '200':
          description: Producto actualizado
        '401':
          description: No autenticado
        '404':
          description: Producto no encontrado

    delete:
      tags:
        - Productos
      summary: Eliminar producto
      description: Eliminar producto (soft delete). Requiere autenticación.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: Producto eliminado
        '401':
          description: No autenticado
        '404':
          description: Producto no encontrado

  /categorias:
    get:
      tags:
        - Categorías
      summary: Listar categorías
      description: Obtener árbol de categorías
      parameters:
        - name: parent_id
          in: query
          schema:
            type: integer
        - name: status
          in: query
          schema:
            type: string
            enum: [active, inactive]
      responses:
        '200':
          description: Lista de categorías
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Category'

  /carrito/{sessionId}/agregar:
    post:
      tags:
        - Carrito
      summary: Añadir al carrito
      description: Añadir producto al carrito de compras
      parameters:
        - name: sessionId
          in: path
          required: true
          schema:
            type: string
          description: ID de sesión del carrito
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - product_id
                - quantity
              properties:
                product_id:
                  type: integer
                  example: 123
                quantity:
                  type: integer
                  minimum: 1
                  example: 2
                variation_id:
                  type: integer
                  nullable: true
      responses:
        '200':
          description: Producto añadido al carrito
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
                    properties:
                      cart_count:
                        type: integer
                      item_total:
                        type: number
        '400':
          description: Producto sin stock

  /pedidos:
    post:
      tags:
        - Pedidos
      summary: Crear pedido
      description: Crear un nuevo pedido
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - customer
                - shipping_address
                - items
                - payment_method
              properties:
                customer:
                  type: object
                  properties:
                    email:
                      type: string
                      format: email
                    first_name:
                      type: string
                    last_name:
                      type: string
                    phone:
                      type: string
                shipping_address:
                  type: object
                  properties:
                    address:
                      type: string
                    city:
                      type: string
                    postal_code:
                      type: string
                    country:
                      type: string
                items:
                  type: array
                  items:
                    type: object
                    properties:
                      product_id:
                        type: integer
                      quantity:
                        type: integer
                      price:
                        type: number
                payment_method:
                  type: string
                  enum: [credit_card, paypal, bank_transfer]
                shipping_method:
                  type: string
      responses:
        '201':
          description: Pedido creado
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
                    properties:
                      order_id:
                        type: integer
                      order_number:
                        type: string
                      total:
                        type: number

  /sync/productos:
    post:
      tags:
        - Sincronización
      summary: Sincronizar productos
      description: Iniciar sincronización de productos desde plataforma externa
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - source
                - source_url
                - api_key
              properties:
                source:
                  type: string
                  enum: [woocommerce, prestashop, shopify, magento]
                  example: "woocommerce"
                source_url:
                  type: string
                  example: "https://mitienda.com"
                api_key:
                  type: string
                api_secret:
                  type: string
                options:
                  type: object
                  properties:
                    update_prices:
                      type: boolean
                    update_stock:
                      type: boolean
                    import_images:
                      type: boolean
      responses:
        '202':
          description: Sincronización iniciada
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  data:
                    type: object
                    properties:
                      job_id:
                        type: string
                      status:
                        type: string
                      estimated_time:
                        type: integer

  /webhooks/woocommerce:
    post:
      tags:
        - Webhooks
      summary: Webhook WooCommerce
      description: Recibir eventos de WooCommerce
      parameters:
        - name: X-WC-Webhook-Source
          in: header
          required: true
          schema:
            type: string
        - name: X-WC-Webhook-Topic
          in: header
          required: true
          schema:
            type: string
        - name: X-WC-Webhook-Signature
          in: header
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: Payload según evento de WooCommerce
      responses:
        '200':
          description: Webhook procesado
        '401':
          description: Firma inválida

security:
  - {}
  - bearerAuth: []

