openapi: 3.1.0
info:
  title: BloomCore API - Integration Webhooks
  version: 1.0.0
  description: |
    Подписанный webhook `integration.failed` для безопасной передачи операционного
    состояния ошибок API, импорта, POS, внешних сервисов и исходящих webhook-ов.

    Все CRM `id` и `*_id` являются UUID; внутренние bigint ID не отправляются.
    Diagnostic payload/context в событие не входят. Message очищается от типовых
    secrets, а request URL содержит только `scheme://host[:port]/path` без
    credentials, query и fragment. Несмотря на очистку, payload содержит
    операционные данные и должен храниться только в защищенной observability-системе.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1
    variables:
      tenant_subdomain:
        default: demo
        description: Поддомен магазина или tenant-контекста.
paths: {}
webhooks:
  integrationFailed:
    post:
      summary: Зафиксирована ошибка интеграции
      description: |
        Получатель обязан проверить HMAC до JSON parsing, дедуплицировать событие
        по `event_id`, проверить UUID tenant/store и не использовать external_id
        как CRM relation. Полное тело нельзя записывать в открытые логи.
      parameters:
        - $ref: '#/components/parameters/webhookEvent'
        - $ref: '#/components/parameters/webhookEventId'
        - $ref: '#/components/parameters/webhookDeliveryId'
        - $ref: '#/components/parameters/webhookTimestamp'
        - $ref: '#/components/parameters/webhookSignature'
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/IntegrationFailedWebhookEnvelope'}
            example:
              event: integration.failed
              event_id: 019f58c6-0913-79eb-aed9-a20d0b255c9f
              created_at: '2026-07-18T09:00:00+00:00'
              payload_schema_version: crm.webhook.v1
              tenant_id: 019f58c1-cc38-75aa-afd8-bdf3dc77fa2c
              store_id: 019f58c1-e3da-72f7-baad-f67b453fe468
              retry_count: 0
              data:
                integration_failure:
                  id: 019f58c6-170e-7ca0-bc88-bba4fa57f195
                  tenant_id: 019f58c1-cc38-75aa-afd8-bdf3dc77fa2c
                  store_id: 019f58c1-e3da-72f7-baad-f67b453fe468
                  webhook_delivery_id: null
                  source: import
                  provider: posiflora
                  operation: import.orders
                  severity: error
                  status: open
                  deduplication_key: import-orders-2026-07-18
                  external_id: batch-125
                  message: Provider returned an authentication error
                  exception_class: RuntimeException
                  request_method: POST
                  request_url: https://example.test/import/orders
                  response_status_code: 401
                  occurrence_count: 1
                  occurred_at: '2026-07-18T08:59:58+00:00'
                  last_seen_at: '2026-07-18T08:59:58+00:00'
                  resolved_at: null
                  created_at: '2026-07-18T08:59:58+00:00'
                  updated_at: '2026-07-18T08:59:58+00:00'
      responses:
        '200': {description: Событие принято интеграцией.}
components:
  parameters:
    webhookEvent:
      name: X-CRM-Webhook-Event
      in: header
      required: true
      schema: {type: string, const: integration.failed}
    webhookEventId:
      name: X-CRM-Webhook-Id
      in: header
      required: true
      schema: {type: string, format: uuid}
    webhookDeliveryId:
      name: X-CRM-Webhook-Delivery
      in: header
      required: true
      schema: {type: string, format: uuid}
    webhookTimestamp:
      name: X-CRM-Webhook-Timestamp
      in: header
      required: true
      schema: {type: string, pattern: '^[0-9]{10}$'}
    webhookSignature:
      name: X-CRM-Webhook-Signature
      in: header
      required: true
      schema: {type: string, pattern: '^sha256=[a-f0-9]{64}$'}
  schemas:
    IntegrationFailedWebhookEnvelope:
      type: object
      additionalProperties: false
      required: [event, event_id, created_at, payload_schema_version, tenant_id, store_id, retry_count, data]
      properties:
        event: {type: string, const: integration.failed}
        event_id:
          type: string
          format: uuid
        created_at: {type: string, format: date-time}
        payload_schema_version: {type: string, const: crm.webhook.v1}
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        retry_count: {type: integer, minimum: 0}
        data: {$ref: '#/components/schemas/IntegrationFailedWebhookData'}
    IntegrationFailedWebhookData:
      type: object
      additionalProperties: false
      required: [integration_failure]
      properties:
        integration_failure: {$ref: '#/components/schemas/IntegrationFailureWebhookFailure'}
    IntegrationFailureWebhookFailure:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, webhook_delivery_id, source, provider, operation, severity, status, deduplication_key, external_id, message, exception_class, request_method, request_url, response_status_code, occurrence_count, occurred_at, last_seen_at, resolved_at, created_at, updated_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        webhook_delivery_id:
          type: [string, 'null']
          format: uuid
        source: {type: string, enum: [webhook_delivery, api, pos, import, external_service]}
        provider: {type: [string, 'null']}
        operation: {type: string, minLength: 1}
        severity: {type: string, enum: [warning, error, critical]}
        status: {type: string, enum: [open, resolved, ignored]}
        deduplication_key: {type: [string, 'null']}
        external_id:
          type: [string, 'null']
          description: Не является CRM UUID; внешний идентификатор провайдера или операции.
        message:
          type: string
          minLength: 1
          description: Очищенное сообщение; не гарантируется отсутствие всех бизнес-данных.
        exception_class: {type: [string, 'null']}
        request_method: {type: [string, 'null'], pattern: '^[A-Z]{3,10}$'}
        request_url:
          type: [string, 'null']
          pattern: '^https?://[^/?#]+(?:/[^?#]*)?$'
          description: Только scheme, host, optional port и path; credentials, query и fragment удалены.
        response_status_code: {type: [integer, 'null'], minimum: 100, maximum: 599}
        occurrence_count: {type: integer, minimum: 1}
        occurred_at: {type: string, format: date-time}
        last_seen_at: {type: [string, 'null'], format: date-time}
        resolved_at: {type: [string, 'null'], format: date-time}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
