openapi: 3.1.0
info:
  title: API de Yolani
  version: 1.1.0
  description: |
    API publica de Yolani: contactos, conversaciones, embudo, mensajes
    omnicanal, plantillas de WhatsApp, agente IA y alta de webhooks por REST
    Hook para cualquier integracion.

    Autenticacion: API key de la empresa en el header
    `Authorization: Bearer yol_...`. La crea el dueno o un administrador en
    Configuracion > Desarrolladores > API Keys. Incluida en los planes Escala y
    Enterprise (y en Corporativo para quien ya lo tiene contratado).

    Limites: 300 peticiones por minuto por empresa (headers X-RateLimit-*) y
    800 peticiones cada 15 minutos por IP de origen (headers RateLimit-*).

    Documentacion completa: https://docs.yolani.co/docs/api/introduccion
servers:
  - url: https://api.yolani.co/api/v1
security:
  - apiKey: []
tags:
  - name: Metadatos
    description: Probar la API key y consultar el catalogo de eventos de webhook.
  - name: Contactos
    description: Listar, crear y actualizar los contactos del CRM.
  - name: Conversaciones
    description: Listar, abrir y cambiar el estado de las conversaciones.
  - name: Mensajes
    description: Leer y enviar mensajes por el canal de cada conversacion.
  - name: Plantillas
    description: Plantillas aprobadas de WhatsApp API.
  - name: Agente IA
    description: Encender o pausar al agente en una conversacion.
  - name: Embudo
    description: Embudos, etapas y mover una conversacion de etapa.
  - name: Webhooks
    description: Alta y baja de webhooks por la API (REST Hook) y ejemplos de eventos.
components:
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      description: "API key de empresa con formato yol_ + 40 caracteres (Configuracion > Desarrolladores > API Keys)."
  parameters:
    Id:
      name: id
      in: path
      required: true
      schema:
        type: integer
        minimum: 1
    Limit:
      name: limit
      in: query
      description: Resultados por pagina (1 a 100).
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 50
    Offset:
      name: offset
      in: query
      description: Cuantos resultados saltar.
      schema:
        type: integer
        minimum: 0
        default: 0
  headers:
    X-RateLimit-Bucket:
      description: Contador por empresa (public_api).
      schema:
        type: string
    X-RateLimit-Limit:
      description: Peticiones por minuto permitidas a la empresa.
      schema:
        type: integer
    X-RateLimit-Remaining:
      description: Peticiones que le quedan a la empresa en el ultimo minuto.
      schema:
        type: integer
    Retry-After:
      description: Segundos a esperar antes de reintentar (solo en 429).
      schema:
        type: integer
  schemas:
    Error:
      type: object
      required: [success, error]
      properties:
        success:
          type: boolean
          const: false
        error:
          type: object
          required: [code, message]
          properties:
            code:
              type: string
              examples: [VALIDATION_ERROR]
            message:
              type: string
              examples: ["phone o email requerido"]
    RateLimitError:
      type: object
      description: |
        Respuesta 429. Con el limite de la empresa trae code, bucket, limit y
        windowMs; con el limite por IP solo success y error.
      properties:
        success:
          type: boolean
          const: false
        code:
          type: string
          const: RATE_LIMIT_PUBLIC_API
        error:
          type: string
        bucket:
          type: string
          const: public_api
        limit:
          type: integer
        windowMs:
          type: integer
    SubscriptionError:
      type: object
      description: 403 de los endpoints de envio cuando la suscripcion no esta vigente.
      properties:
        error:
          type: string
        code:
          type: string
          enum: [TRIAL_EXPIRED, INACTIVE_SUBSCRIPTION, ACCOUNT_SUSPENDED, ADMIN_GRANT_EXPIRED, SUB_ACCOUNT_SUSPENDED, NO_SUBSCRIPTION]
        status:
          type: string
        requiresPayment:
          type: boolean
    Meta:
      type: object
      properties:
        total:
          type: integer
        limit:
          type: integer
        offset:
          type: integer
    Contact:
      type: object
      properties:
        id:
          type: integer
        name:
          type: [string, "null"]
        phone:
          type: [string, "null"]
          description: Telefono capturado aparte, tal como se escribio; en contactos de WhatsApp suele venir null (el numero esta en whatsapp_id).
        email:
          type: [string, "null"]
        whatsapp_id:
          type: [string, "null"]
          description: Numero de WhatsApp, solo digitos con codigo de pais (Mexico 521 + 10 digitos). null en contactos de Instagram y Facebook; empieza con api_ si el contacto se creo solo con correo.
        tags:
          type: array
          items:
            type: string
        created_at:
          type: [string, "null"]
          format: date-time
        updated_at:
          type: [string, "null"]
          format: date-time
    Conversation:
      type: object
      properties:
        id:
          type: integer
        contact_id:
          type: integer
        channel:
          type: [string, "null"]
          enum: [whatsapp, instagram, facebook, web_widget, null]
        status:
          type: [string, "null"]
          enum: [active, waiting, resolved, handed_off, null]
        bot_enabled:
          type: boolean
          description: false cuando status es handed_off (agente IA pausado).
        assigned_to_user_id:
          type: [integer, "null"]
        last_message_at:
          type: [string, "null"]
          format: date-time
        created_at:
          type: [string, "null"]
          format: date-time
    Message:
      type: object
      properties:
        id:
          type: integer
        conversation_id:
          type: integer
        direction:
          type: string
          enum: [inbound, outbound]
        channel:
          type: [string, "null"]
          enum: [whatsapp, instagram, facebook, web_widget, null]
        type:
          type: string
          enum: [text, image, audio, video, document, location, sticker]
        content:
          type: [string, "null"]
        media_url:
          type: [string, "null"]
          description: Ruta del archivo dentro de Yolani (/api/media/...). No se descarga con la API key.
        status:
          type: [string, "null"]
          enum: [pending, sent, delivered, read, played, failed, null]
        sent_by_bot:
          type: boolean
        created_at:
          type: [string, "null"]
          format: date-time
    SentMessage:
      type: object
      properties:
        message_id:
          type: integer
        conversation_id:
          type: integer
        channel:
          type: string
        type:
          type: string
          enum: [text, image, audio, video, document]
        status:
          type: string
          enum: [sent, pending, failed]
          description: failed = el canal no lo acepto (el mensaje queda guardado como fallido).
        already_processed:
          type: boolean
          description: Solo en texto. true si ya existia un mensaje con ese client_request_id.
    ContactResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          $ref: "#/components/schemas/Contact"
    ContactUpsertResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          $ref: "#/components/schemas/Contact"
        meta:
          type: object
          properties:
            created:
              type: boolean
    ConversationResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          $ref: "#/components/schemas/Conversation"
    SentMessageResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          $ref: "#/components/schemas/SentMessage"
    Subscription:
      type: object
      properties:
        id:
          type: integer
        url:
          type: string
        events:
          type: array
          items:
            type: string
        origen:
          type: string
          enum: [zapier, make, api]
        enabled:
          type: boolean
        created_at:
          type: string
          format: date-time
    Pipeline:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        is_default:
          type: boolean
        stages:
          type: array
          items:
            type: object
            properties:
              id:
                type: integer
              name:
                type: string
              position:
                type: integer
              is_final:
                type: boolean
              pipeline_id:
                type: integer
              pipeline_name:
                type: string
    Template:
      type: object
      properties:
        name:
          type: string
        language:
          type: string
        category:
          type: string
        body:
          type: [string, "null"]
        header_format:
          type: [string, "null"]
          examples: [TEXT, IMAGE, VIDEO, DOCUMENT]
        header_text:
          type: [string, "null"]
        footer:
          type: [string, "null"]
        buttons:
          type: array
          items:
            type: object
            properties:
              type:
                type: string
                examples: [URL, QUICK_REPLY, PHONE_NUMBER, COPY_CODE]
              text:
                type: [string, "null"]
              url:
                type: [string, "null"]
              phoneNumber:
                type: [string, "null"]
              urlHasVariable:
                type: boolean
              example:
                type: [string, "null"]
  responses:
    BadRequest:
      description: Validacion fallida (VALIDATION_ERROR) o cuerpo que no es JSON.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    Unauthorized:
      description: API key faltante (MISSING_API_KEY) o invalida, revocada o expirada (INVALID_API_KEY).
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    Forbidden:
      description: El plan no incluye la API (MODULE_NOT_ENABLED) o la key no tiene el scope (INSUFFICIENT_SCOPE).
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    ForbiddenOrInactive:
      description: |
        MODULE_NOT_ENABLED o INSUFFICIENT_SCOPE (schema Error), o suscripcion
        no vigente (schema SubscriptionError).
      content:
        application/json:
          schema:
            oneOf:
              - $ref: "#/components/schemas/Error"
              - $ref: "#/components/schemas/SubscriptionError"
    NotFound:
      description: El recurso no existe o no es de tu empresa (NOT_FOUND).
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    TooManyRequests:
      description: Limite de peticiones superado.
      headers:
        Retry-After:
          $ref: "#/components/headers/Retry-After"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/RateLimitError"
paths:
  /me:
    get:
      tags: [Metadatos]
      summary: Verificar la API key
      description: Funciona con cualquier key valida, sin scope.
      operationId: getMe
      responses:
        "200":
          description: Empresa y datos de la key
          headers:
            X-RateLimit-Bucket:
              $ref: "#/components/headers/X-RateLimit-Bucket"
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      company:
                        type: object
                        properties:
                          id:
                            type: integer
                          name:
                            type: [string, "null"]
                      api_key:
                        type: object
                        properties:
                          name:
                            type: [string, "null"]
                          prefix:
                            type: [string, "null"]
                            examples: [yol_abcdefgh]
                          scopes:
                            type: array
                            items:
                              type: string
                            description: '["write"] = acceso completo.'
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /webhooks/event-types:
    get:
      tags: [Metadatos]
      summary: Catalogo de eventos de webhook
      description: Funciona con cualquier key valida, sin scope. Los webhooks se configuran en el panel.
      operationId: listEventTypes
      responses:
        "200":
          description: Eventos que existen
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      event_types:
                        type: array
                        items:
                          type: string
                        examples:
                          - [test.ping, conversation.created, conversation.updated, conversation.closed, conversation.bot.enabled, conversation.bot.disabled, message.received, message.sent, contact.created, contact.updated, appointment.created, appointment.rescheduled, appointment.cancelled, conversation.stage_changed]
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /webhooks:
    get:
      tags: [Webhooks]
      summary: Listar los webhooks dados de alta por la API
      operationId: listSubscriptions
      description: "Scope: webhooks:manage. No incluye los creados en el panel."
      responses:
        "200":
          description: Webhooks dados de alta por API keys de la empresa
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Subscription"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Webhooks]
      summary: Dar de alta un webhook (REST Hook)
      operationId: subscribeWebhook
      description: |
        Scope: webhooks:manage, mas el de lectura de cada evento (contact.* ->
        contacts:read; el resto -> conversations:read). Recibe eventos de todos
        los canales, con la misma firma y reintentos que uno del panel. Deja de
        recibir si la API key que lo creo se revoca o vence. Tope: 100 por empresa.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                url:
                  type: string
                  format: uri
                  description: https y publica. Tambien se acepta target_url.
                events:
                  type: array
                  items:
                    type: string
                  description: Eventos de GET /webhooks/event-types. Con uno solo se puede mandar event.
                event:
                  type: string
                origen:
                  type: string
                  enum: [zapier, make, api]
                  description: Cualquier otro valor queda como api.
      responses:
        "201":
          description: Webhook creado; secret solo viene en esta respuesta
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    allOf:
                      - $ref: "#/components/schemas/Subscription"
                      - type: object
                        properties:
                          secret:
                            type: string
                            examples: [whk_3c9f0e]
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: La empresa ya tiene 100 webhooks dados de alta por API (SUBSCRIPTION_LIMIT)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /webhooks/{id}:
    parameters:
      - $ref: "#/components/parameters/Id"
    delete:
      tags: [Webhooks]
      summary: Dar de baja un webhook dado de alta por la API
      operationId: unsubscribeWebhook
      description: "Scope: webhooks:manage. Los creados en el panel responden 404."
      responses:
        "200":
          description: Webhook borrado
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      id:
                        type: integer
                      deleted:
                        type: boolean
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /webhooks/samples:
    get:
      tags: [Webhooks]
      summary: Ejemplos de un evento con datos de la cuenta
      operationId: listEventSamples
      description: |
        Scope: el de lectura del evento. Hasta 3 eventos con la forma del webhook
        y sample = true; sin datos de ese tipo, un ejemplo fijo.
      parameters:
        - name: event
          in: query
          required: true
          schema:
            type: string
            enum: [contact.created, contact.updated, appointment.created, appointment.rescheduled, appointment.cancelled, conversation.stage_changed, message.received]
      responses:
        "200":
          description: Eventos de ejemplo
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        event_id:
                          type: string
                        event_type:
                          type: string
                        occurred_at:
                          type: string
                          format: date-time
                        sample:
                          type: boolean
                          const: true
                        data:
                          type: object
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /pipelines:
    get:
      tags: [Embudo]
      summary: Listar embudos y etapas
      operationId: listPipelines
      description: "Scope: conversations:read. Embudos activos con sus etapas activas, en orden."
      responses:
        "200":
          description: Embudos
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Pipeline"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /conversations/{id}/stage:
    parameters:
      - $ref: "#/components/parameters/Id"
    post:
      tags: [Embudo]
      summary: Mover una conversacion de etapa
      operationId: moveConversationStage
      description: |
        Scope: conversations:write. Queda en el historial, corre las acciones
        automaticas de la etapa y emite conversation.stage_changed con source
        system. Una etapa de otro embudo cambia la conversacion de embudo.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [stage_id]
              properties:
                stage_id:
                  type: integer
      responses:
        "200":
          description: Etapa actualizada
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      conversation_id:
                        type: integer
                      stage_id:
                        type: [integer, "null"]
                      stage_name:
                        type: [string, "null"]
                      pipeline_id:
                        type: [integer, "null"]
                      previous_stage_id:
                        type: [integer, "null"]
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: Conversacion no encontrada (NOT_FOUND) o etapa inexistente o inactiva (STAGE_NOT_FOUND)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /contacts:
    get:
      tags: [Contactos]
      summary: Listar contactos
      operationId: listContacts
      description: |
        Scope: contacts:read. Los mas recientes primero. No incluye visitantes
        anonimos del chat web, grupos, chats personales ni contactos fusionados.
        Hoy tampoco los contactos que solo escribieron por Instagram o Facebook
        (se consultan por id), y si incluye contactos borrados en el panel.
      parameters:
        - name: search
          in: query
          description: Busca un texto dentro del nombre, el correo o el telefono. No distingue mayusculas, si acentos.
          schema:
            type: string
        - name: phone
          in: query
          description: Telefono exacto en cualquier formato (+52 1 55..., 55..., 521...); sin codigo de pais se toma como Mexico.
          schema:
            type: string
        - name: email
          in: query
          description: Correo exacto, sin distinguir mayusculas.
          schema:
            type: string
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/Offset"
      responses:
        "200":
          description: Lista de contactos
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Contact"
                  meta:
                    $ref: "#/components/schemas/Meta"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/TooManyRequests"
    post:
      tags: [Contactos]
      summary: Crear o actualizar contacto (upsert por telefono o correo)
      operationId: upsertContact
      description: |
        Scope: contacts:write. Busca por telefono (en cualquiera de sus formas)
        y luego por correo; si existe lo actualiza, si no lo crea. El telefono
        acepta cualquier formato (sin codigo de pais se toma como Mexico) y queda
        en whatsapp_id como lo entrega WhatsApp.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                phone:
                  type: string
                  examples: ["5215512345678"]
                email:
                  type: string
                name:
                  type: string
              anyOf:
                - required: [phone]
                - required: [email]
      responses:
        "200":
          description: Contacto actualizado (meta.created = false)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactUpsertResponse"
        "201":
          description: Contacto creado (meta.created = true)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactUpsertResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /contacts/{id}:
    parameters:
      - $ref: "#/components/parameters/Id"
    get:
      tags: [Contactos]
      summary: Consultar contacto
      operationId: getContact
      description: "Scope: contacts:read"
      responses:
        "200":
          description: Contacto
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
    patch:
      tags: [Contactos]
      summary: Actualizar contacto
      operationId: updateContact
      description: |
        Scope: contacts:write. Solo cambia los campos enviados; null o vacio
        borra el campo. Un nombre puesto por la API cuenta como manual (el agente
        no lo reemplaza).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: [string, "null"]
                email:
                  type: [string, "null"]
                phone:
                  type: [string, "null"]
      responses:
        "200":
          description: Contacto actualizado
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ContactResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /conversations:
    get:
      tags: [Conversaciones]
      summary: Listar conversaciones
      operationId: listConversations
      description: "Scope: conversations:read. Ordenadas por ultimo mensaje, la mas reciente primero."
      parameters:
        - name: status
          in: query
          schema:
            type: string
            enum: [active, waiting, resolved, handed_off]
        - name: channel
          in: query
          schema:
            type: string
            enum: [whatsapp, instagram, facebook, web_widget]
        - name: contact_id
          in: query
          schema:
            type: integer
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/Offset"
      responses:
        "200":
          description: Lista de conversaciones
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Conversation"
                  meta:
                    $ref: "#/components/schemas/Meta"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/TooManyRequests"
    post:
      tags: [Conversaciones]
      summary: Abrir (o reactivar) una conversacion de WhatsApp por telefono
      operationId: createConversation
      description: |
        Scope: conversations:write. Requiere suscripcion vigente. Crea el
        contacto si no existe; reutiliza su conversacion mas reciente (la reabre
        si estaba resuelta) o crea una en la primera etapa del embudo. El envio
        de initial_message es de mejor esfuerzo: si falla, la conversacion se
        crea igual y la respuesta no lo indica.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [phone]
              properties:
                phone:
                  type: string
                  description: Numero con codigo de pais (minimo 8 digitos). Se ignoran +, espacios y guiones.
                  examples: ["5215512345678"]
                name:
                  type: string
                initial_message:
                  type: string
      responses:
        "201":
          description: Conversacion creada o reutilizada
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ConversationResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/ForbiddenOrInactive"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /conversations/{id}:
    parameters:
      - $ref: "#/components/parameters/Id"
    get:
      tags: [Conversaciones]
      summary: Consultar conversacion
      operationId: getConversation
      description: "Scope: conversations:read"
      responses:
        "200":
          description: Conversacion
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ConversationResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
    patch:
      tags: [Conversaciones]
      summary: Cambiar el estado de la conversacion
      operationId: updateConversationStatus
      description: |
        Scope: conversations:write. Estados: active, waiting, resolved. Para
        pausar al agente usa POST /conversations/{id}/bot. Si estaba en
        handed_off, pasarla a otro estado vuelve a encender al agente. Dispara
        conversation.updated y, al resolver, conversation.closed.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [status]
              properties:
                status:
                  type: string
                  enum: [active, waiting, resolved]
      responses:
        "200":
          description: Conversacion actualizada
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ConversationResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /conversations/{id}/messages:
    parameters:
      - $ref: "#/components/parameters/Id"
    get:
      tags: [Mensajes]
      summary: Listar mensajes de una conversacion
      operationId: listMessages
      description: "Scope: conversations:read. Los mas recientes primero."
      parameters:
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/Offset"
      responses:
        "200":
          description: Lista de mensajes
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Message"
                  meta:
                    $ref: "#/components/schemas/Meta"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
    post:
      tags: [Mensajes]
      summary: Enviar mensaje (texto o archivo)
      operationId: sendMessage
      description: |
        Scope: messages:send. Requiere suscripcion vigente. Manda `text` o
        `media_url` (si van los dos, solo se envia el archivo). Yolani descarga
        media_url (maximo 15 MB, 20 s, URL publica). `client_request_id` evita
        duplicados en texto. Un envio que el canal rechaza responde 201 con
        status failed. El mensaje cuenta como de una persona del equipo: el
        agente se aparta el rato de "Cuando contestas tu" (30 min por omision);
        POST /conversations/{id}/bot con enabled true lo cancela.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                text:
                  type: string
                media_url:
                  type: string
                  format: uri
                caption:
                  type: string
                filename:
                  type: string
                client_request_id:
                  type: string
              anyOf:
                - required: [text]
                - required: [media_url]
      responses:
        "200":
          description: Mensaje ya procesado antes con ese client_request_id (already_processed = true)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SentMessageResponse"
        "201":
          description: Mensaje registrado; revisa data.status (sent, pending o failed)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SentMessageResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/ForbiddenOrInactive"
        "404":
          $ref: "#/components/responses/NotFound"
        "413":
          description: El archivo pasa de 15 MB (MEDIA_TOO_LARGE)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "422":
          description: No se pudo descargar media_url (MEDIA_DOWNLOAD_FAILED) o el numero no tiene WhatsApp (WHATSAPP_NUMBER_NOT_REGISTERED)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /templates:
    get:
      tags: [Plantillas]
      summary: Listar plantillas aprobadas de WhatsApp API
      operationId: listTemplates
      description: |
        Scope: messages:send_template. Solo las APPROVED de la cuenta de
        WhatsApp API principal. Sin WhatsApp API conectado devuelve una lista vacia.
      responses:
        "200":
          description: Plantillas aprobadas
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Template"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /conversations/{id}/messages/template:
    parameters:
      - $ref: "#/components/parameters/Id"
    post:
      tags: [Plantillas]
      summary: Enviar una plantilla
      operationId: sendTemplate
      description: |
        Scope: messages:send_template. Requiere suscripcion vigente y WhatsApp
        API conectado con la plantilla aprobada. Si la conversacion sale por
        WhatsApp API se envia la plantilla real (delivery_mode = template); en
        WhatsApp Web, Instagram, Facebook o chat web se envia el cuerpo como
        texto con las variables reemplazadas (delivery_mode = text_fallback).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [template_name]
              properties:
                template_name:
                  type: string
                language:
                  type: string
                  examples: [es_MX]
                body_params:
                  type: array
                  items:
                    type: string
                header_param:
                  type: string
                  description: Valor de la variable del encabezado de texto, o URL publica si el encabezado es multimedia. Solo con delivery_mode template.
                button_params:
                  type: array
                  items:
                    type: string
                  description: Valores de botones con URL variable o codigo de cupon, en orden. Solo con delivery_mode template.
                client_request_id:
                  type: string
                  description: Solo aplica con delivery_mode text_fallback.
      responses:
        "201":
          description: Plantilla enviada
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      message_id:
                        type: integer
                      conversation_id:
                        type: integer
                      channel:
                        type: string
                      delivery_mode:
                        type: string
                        enum: [template, text_fallback]
                      status:
                        type: string
        "400":
          description: |
            VALIDATION_ERROR, WHATSAPP_API_NOT_CONFIGURED, WABA_CREDENTIALS_MISSING,
            TEMPLATE_NOT_APPROVED, TEMPLATE_PARAMS_MISMATCH,
            TEMPLATE_HEADER_PARAM_REQUIRED, TEMPLATE_HEADER_MEDIA_REQUIRED,
            TEMPLATE_HEADER_UNSUPPORTED o TEMPLATE_BUTTON_PARAMS_MISMATCH
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/ForbiddenOrInactive"
        "404":
          description: Conversacion no encontrada (NOT_FOUND) o plantilla inexistente (TEMPLATE_NOT_FOUND)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /conversations/{id}/bot:
    parameters:
      - $ref: "#/components/parameters/Id"
    post:
      tags: [Agente IA]
      summary: Encender o pausar el agente IA
      operationId: toggleBot
      description: |
        Scope: bot:manage. Pausar deja la conversacion en handed_off, corta la
        respuesta en curso y programa el regreso del agente segun la cuenta.
        Encender la deja en active. Dispara conversation.bot.enabled o
        conversation.bot.disabled.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [enabled]
              properties:
                enabled:
                  type: boolean
                reason:
                  type: string
                  description: Motivo de la pausa. Por defecto "Pausado via API".
      responses:
        "200":
          description: Estado del agente actualizado
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      conversation_id:
                        type: integer
                      bot_enabled:
                        type: boolean
                      assistant_id:
                        type: integer
                        description: Solo al encender.
        "400":
          description: VALIDATION_ERROR o NO_ASSISTANT (la cuenta no tiene agente activo)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
