openapi: 3.1.0
info:
  title: Wasabi API
  version: "1.0"
  description: |
    Партнёрский API цифрового магазина **Wasabi**: каталог подписок, игр и кодов пополнения.
    Заказ, списание с баланса партнёра и выдача товара происходят **одним запросом** —
    в ответе на `POST /v1/orders` вы сразу получаете аккаунт, код или подтверждение пополнения.

    ## Аутентификация

    Все запросы требуют API-ключ в заголовке `Authorization`:

    ```http
    Authorization: Bearer wsb_live_9f2c4a7e1b8d3f6a
    ```

    Ключи бывают двух видов: `wsb_live_…` — боевые, `wsb_test_…` — тестовые.
    Выпустить и отозвать ключ можно в личном кабинете партнёра. Не передавайте ключ
    во фронтенд и не храните его в репозитории.

    ## Идемпотентность

    Передавайте заголовок `Idempotency-Key` (любая уникальная строка до 64 символов, например UUID)
    при создании заказа. Повторный запрос с тем же ключом вернёт уже созданный заказ
    и **не спишет деньги повторно** — так безопасно повторять запросы при обрыве сети.
    Ключ хранится 24 часа. Если с тем же ключом прислать другое тело запроса, API вернёт `409 idempotency_conflict`.

    ## Вебхуки

    Укажите URL в личном кабинете — Wasabi будет отправлять `POST` с событиями
    (`order.delivered`, `order.processing`, `order.failed`, `balance.topup`).
    Каждый запрос подписан: заголовок `X-Wasabi-Signature` содержит HMAC-SHA256
    от тела запроса, вычисленный секретом вебхука (`whsec_…`), в hex.

    ```
    X-Wasabi-Signature: t=1764763200,v1=5f8a3c…e91b
    ```

    Подпись считается от строки `{t}.{raw_body}`. Сравнивайте подписи в постоянном времени
    и отклоняйте события старше 5 минут. Если ваш сервер не ответил `2xx`, доставка повторяется
    с экспоненциальной задержкой (1 мин, 5 мин, 30 мин, 2 ч, 6 ч…) до 24 часов, пока не будет получен `2xx`.
    События могут прийти повторно — обрабатывайте их идемпотентно по `data.id`.

    ## Тестовый режим

    С ключом `wsb_test_…` API работает так же, как боевой, но без реальных списаний и закупок:
    заказы выдают тестовые данные, баланс виртуальный, вебхуки отправляются на тестовый URL.
    Тестовые и боевые данные полностью изолированы.

    ## MCP

    Для ИИ-агентов (Claude, ChatGPT, Cursor и других) доступен MCP-сервер:

    ```
    https://api.wasabi.guru/mcp
    ```

    Авторизация — тем же Bearer-ключом. Инструменты:

    | Инструмент | Что делает |
    |---|---|
    | `search_products` | Поиск по каталогу с фильтром по категории |
    | `create_order` | Создание заказа с выдачей товара |
    | `get_order` | Статус и содержимое заказа |
    | `get_balance` | Текущий баланс партнёра |

    Рекомендуем выдавать агенту тестовый ключ, пока сценарий не отлажен.
  contact:
    name: Поддержка Wasabi
    url: https://wasabi.guru
servers:
  - url: https://api.wasabi.guru
    description: Боевой и тестовый режим (определяется ключом)
security:
  - bearerAuth: []
tags:
  - name: Каталог
    description: Товары, цены, наличие и данные, необходимые для заказа.
  - name: Заказы
    description: Создание заказа с мгновенной выдачей и просмотр истории.
  - name: Баланс
    description: Баланс партнёра и история операций.
  - name: Вебхуки
    description: События, которые Wasabi отправляет на ваш сервер.

paths:
  /v1/products:
    get:
      tags: [Каталог]
      operationId: listProducts
      summary: Список товаров
      description: Возвращает товары каталога с ценами для партнёра. Поддерживает фильтр по категории, поиск и постраничный вывод.
      parameters:
        - name: category
          in: query
          description: Категория товаров.
          schema:
            $ref: "#/components/schemas/Category"
          example: ai
        - name: q
          in: query
          description: Поиск по названию.
          schema:
            type: string
          example: chatgpt
        - name: page
          in: query
          description: Номер страницы, начиная с 1.
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: limit
          in: query
          description: Количество товаров на странице.
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
      responses:
        "200":
          description: Список товаров.
          content:
            application/json:
              schema:
                type: object
                required: [data, page, limit, total]
                properties:
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Product"
                  page:
                    type: integer
                    example: 1
                  limit:
                    type: integer
                    example: 20
                  total:
                    type: integer
                    description: Всего товаров по фильтру.
                    example: 3
              example:
                data:
                  - id: chatgpt-plus-1m
                    name: ChatGPT Plus — 1 месяц
                    category: ai
                    type: account
                    price: 1990
                    currency: RUB
                    in_stock: true
                    fields:
                      - name: email
                        label: Email для аккаунта
                        type: email
                        required: true
                  - id: claude-pro-1m
                    name: Claude Pro — 1 месяц
                    category: ai
                    type: account
                    price: 2190
                    currency: RUB
                    in_stock: true
                    fields:
                      - name: email
                        label: Email для аккаунта
                        type: email
                        required: true
                  - id: midjourney-basic-1m
                    name: Midjourney Basic — 1 месяц
                    category: ai
                    type: code
                    price: 1090
                    currency: RUB
                    in_stock: false
                    fields: []
                page: 1
                limit: 20
                total: 3
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"

  /v1/products/{id}:
    get:
      tags: [Каталог]
      operationId: getProduct
      summary: Товар по ID
      description: Возвращает карточку товара с ценой, наличием и списком полей, которые нужно передать при заказе.
      parameters:
        - name: id
          in: path
          required: true
          description: Идентификатор товара.
          schema:
            type: string
          example: steam-topup
      responses:
        "200":
          description: Товар.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Product"
              examples:
                topup:
                  summary: Пополнение Steam
                  value:
                    id: steam-topup
                    name: Пополнение Steam
                    category: topup
                    type: topup
                    price: null
                    currency: RUB
                    min_amount: 100
                    max_amount: 50000
                    fee_percent: 6
                    in_stock: true
                    fields:
                      - name: login
                        label: Логин Steam
                        type: string
                        required: true
                      - name: region
                        label: Регион аккаунта
                        type: string
                        required: false
                        enum: [RU, KZ, CIS]
                account:
                  summary: ChatGPT Plus
                  value:
                    id: chatgpt-plus-1m
                    name: ChatGPT Plus — 1 месяц
                    category: ai
                    type: account
                    price: 1990
                    currency: RUB
                    in_stock: true
                    fields:
                      - name: email
                        label: Email для аккаунта
                        type: email
                        required: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"

  /v1/orders:
    post:
      tags: [Заказы]
      operationId: createOrder
      summary: Создать заказ
      description: |
        Создаёт заказ, списывает сумму с баланса партнёра и сразу выдаёт товар.
        Для большинства товаров ответ приходит со статусом `delivered` и заполненным `item`.
        Если выдача занимает время, заказ вернётся в статусе `processing` — финальный статус придёт вебхуком
        или через `GET /v1/orders/{id}`. При неудачной выдаче средства возвращаются на баланс (`refunded`).
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateOrderRequest"
            examples:
              chatgpt:
                summary: ChatGPT Plus на 1 месяц
                value:
                  product: chatgpt-plus-1m
                  qty: 1
                  fields:
                    email: anna@example.com
                  external_id: shop-10482
              steam:
                summary: Пополнение Steam на 1000 ₽
                value:
                  product: steam-topup
                  amount: 1000
                  fields:
                    login: player_one
                  external_id: shop-10483
      responses:
        "201":
          description: Заказ создан.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Order"
              examples:
                chatgpt:
                  summary: Выдан аккаунт ChatGPT Plus
                  value:
                    id: ord_8KQ2
                    status: delivered
                    product: chatgpt-plus-1m
                    qty: 1
                    external_id: shop-10482
                    charged: 1990
                    currency: RUB
                    balance: 86400
                    item:
                      type: account
                      login: anna@example.com
                      password: Wq7!rP2m-x9L
                      expires_at: "2027-01-03T12:00:00Z"
                      instructions: Войдите на chatgpt.com с этими данными и смените пароль.
                    created_at: "2026-12-03T12:00:00Z"
                    delivered_at: "2026-12-03T12:00:02Z"
                steam:
                  summary: Пополнение Steam выполнено
                  value:
                    id: ord_8KQ3
                    status: delivered
                    product: steam-topup
                    qty: 1
                    amount: 1000
                    external_id: shop-10483
                    charged: 1060
                    currency: RUB
                    balance: 85340
                    item:
                      type: topup
                      login: player_one
                      amount: 1000
                      currency: RUB
                    created_at: "2026-12-03T12:05:00Z"
                    delivered_at: "2026-12-03T12:05:04Z"
        "200":
          description: Повторный запрос с тем же `Idempotency-Key` — возвращён ранее созданный заказ, повторного списания нет.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Order"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          $ref: "#/components/responses/InsufficientBalance"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/IdempotencyConflict"
        "429":
          $ref: "#/components/responses/RateLimited"
    get:
      tags: [Заказы]
      operationId: listOrders
      summary: Список заказов
      description: Возвращает заказы партнёра от новых к старым. Пагинация курсорная — передайте `next_cursor` из ответа в параметр `cursor`.
      parameters:
        - name: status
          in: query
          description: Фильтр по статусу.
          schema:
            $ref: "#/components/schemas/OrderStatus"
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: Страница заказов.
          content:
            application/json:
              schema:
                type: object
                required: [data, has_more]
                properties:
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Order"
                  has_more:
                    type: boolean
                  next_cursor:
                    type: [string, "null"]
              example:
                data:
                  - id: ord_8KQ3
                    status: delivered
                    product: steam-topup
                    qty: 1
                    amount: 1000
                    external_id: shop-10483
                    charged: 1060
                    currency: RUB
                    balance: 85340
                    item:
                      type: topup
                      login: player_one
                      amount: 1000
                      currency: RUB
                    created_at: "2026-12-03T12:05:00Z"
                    delivered_at: "2026-12-03T12:05:04Z"
                  - id: ord_8KQ2
                    status: delivered
                    product: chatgpt-plus-1m
                    qty: 1
                    external_id: shop-10482
                    charged: 1990
                    currency: RUB
                    balance: 86400
                    item:
                      type: account
                      login: anna@example.com
                      password: Wq7!rP2m-x9L
                      expires_at: "2027-01-03T12:00:00Z"
                    created_at: "2026-12-03T12:00:00Z"
                    delivered_at: "2026-12-03T12:00:02Z"
                has_more: true
                next_cursor: ord_8KQ1
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"

  /v1/orders/{id}:
    get:
      tags: [Заказы]
      operationId: getOrder
      summary: Заказ по ID
      description: Возвращает заказ с текущим статусом и выданным товаром.
      parameters:
        - name: id
          in: path
          required: true
          description: Идентификатор заказа.
          schema:
            type: string
          example: ord_8KQ2
      responses:
        "200":
          description: Заказ.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Order"
              examples:
                code:
                  summary: Выдан код
                  value:
                    id: ord_8KR7
                    status: delivered
                    product: spotify-premium-3m
                    qty: 1
                    external_id: shop-10501
                    charged: 1290
                    currency: RUB
                    balance: 84050
                    item:
                      type: code
                      code: SPOT-7QH4-K9XM-2LPA
                      expires_at: "2027-12-31T23:59:59Z"
                      instructions: Активируйте код на spotify.com/redeem.
                    created_at: "2026-12-03T13:10:00Z"
                    delivered_at: "2026-12-03T13:10:01Z"
                processing:
                  summary: Заказ в обработке
                  value:
                    id: ord_8KR8
                    status: processing
                    product: steam-topup
                    qty: 1
                    amount: 500
                    external_id: shop-10502
                    charged: 530
                    currency: RUB
                    balance: 83520
                    item: null
                    created_at: "2026-12-03T13:12:00Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"

  /v1/balance:
    get:
      tags: [Баланс]
      operationId: getBalance
      summary: Текущий баланс
      description: Возвращает доступный баланс партнёра и сумму, удержанную под заказы в обработке.
      responses:
        "200":
          description: Баланс.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Balance"
              example:
                balance: 85340
                currency: RUB
                held: 530
                updated_at: "2026-12-03T12:05:04Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"

  /v1/balance/transactions:
    get:
      tags: [Баланс]
      operationId: listBalanceTransactions
      summary: История операций
      description: Пополнения, списания за заказы и возвраты, от новых к старым. Пагинация курсорная.
      parameters:
        - name: type
          in: query
          description: Фильтр по типу операции.
          schema:
            $ref: "#/components/schemas/TransactionType"
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: Страница операций.
          content:
            application/json:
              schema:
                type: object
                required: [data, has_more]
                properties:
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Transaction"
                  has_more:
                    type: boolean
                  next_cursor:
                    type: [string, "null"]
              example:
                data:
                  - id: txn_5Hd2
                    type: charge
                    amount: -1060
                    currency: RUB
                    balance_after: 85340
                    order_id: ord_8KQ3
                    description: Пополнение Steam — 1000 ₽
                    created_at: "2026-12-03T12:05:00Z"
                  - id: txn_5Hd1
                    type: charge
                    amount: -1990
                    currency: RUB
                    balance_after: 86400
                    order_id: ord_8KQ2
                    description: ChatGPT Plus — 1 месяц
                    created_at: "2026-12-03T12:00:00Z"
                  - id: txn_5Hc9
                    type: topup
                    amount: 50000
                    currency: RUB
                    balance_after: 88390
                    order_id: null
                    description: Пополнение баланса по счёту №2471
                    created_at: "2026-12-02T09:30:00Z"
                has_more: false
                next_cursor: null
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"

webhooks:
  order.delivered:
    post:
      tags: [Вебхуки]
      operationId: webhookOrderDelivered
      summary: Заказ выдан
      description: Товар успешно выдан. Приходит и для заказов, выданных сразу, и для тех, что были в обработке.
      parameters:
        - $ref: "#/components/parameters/WebhookSignature"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/OrderEvent"
            example:
              event: order.delivered
              created_at: "2026-12-03T12:05:04Z"
              data:
                id: ord_8KQ3
                status: delivered
                product: steam-topup
                qty: 1
                amount: 1000
                external_id: shop-10483
                charged: 1060
                currency: RUB
                balance: 85340
                item:
                  type: topup
                  login: player_one
                  amount: 1000
                  currency: RUB
                created_at: "2026-12-03T12:05:00Z"
                delivered_at: "2026-12-03T12:05:04Z"
      responses:
        "200":
          description: Событие принято. Любой ответ `2xx` останавливает повторы.
  order.processing:
    post:
      tags: [Вебхуки]
      operationId: webhookOrderProcessing
      summary: Заказ в обработке
      description: Выдача товара требует времени. Сумма уже удержана; дождитесь `order.delivered` или `order.failed`.
      parameters:
        - $ref: "#/components/parameters/WebhookSignature"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/OrderEvent"
            example:
              event: order.processing
              created_at: "2026-12-03T13:12:00Z"
              data:
                id: ord_8KR8
                status: processing
                product: steam-topup
                qty: 1
                amount: 500
                external_id: shop-10502
                charged: 530
                currency: RUB
                balance: 83520
                item: null
                created_at: "2026-12-03T13:12:00Z"
      responses:
        "200":
          description: Событие принято.
  order.failed:
    post:
      tags: [Вебхуки]
      operationId: webhookOrderFailed
      summary: Заказ не выполнен
      description: Выдать товар не удалось. Списанная сумма возвращается на баланс, заказ переходит в статус `refunded`.
      parameters:
        - $ref: "#/components/parameters/WebhookSignature"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/OrderEvent"
            example:
              event: order.failed
              created_at: "2026-12-03T13:20:00Z"
              data:
                id: ord_8KR8
                status: refunded
                product: steam-topup
                qty: 1
                amount: 500
                external_id: shop-10502
                charged: 0
                currency: RUB
                balance: 84050
                item: null
                failure:
                  code: account_not_found
                  message: Аккаунт Steam с логином player_two не найден.
                created_at: "2026-12-03T13:12:00Z"
      responses:
        "200":
          description: Событие принято.
  balance.topup:
    post:
      tags: [Вебхуки]
      operationId: webhookBalanceTopup
      summary: Баланс пополнен
      description: На баланс партнёра зачислены средства.
      parameters:
        - $ref: "#/components/parameters/WebhookSignature"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BalanceTopupEvent"
            example:
              event: balance.topup
              created_at: "2026-12-02T09:30:00Z"
              data:
                id: txn_5Hc9
                type: topup
                amount: 50000
                currency: RUB
                balance_after: 88390
                order_id: null
                description: Пополнение баланса по счёту №2471
                created_at: "2026-12-02T09:30:00Z"
      responses:
        "200":
          description: Событие принято.

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: wsb_live_… / wsb_test_…
      description: API-ключ партнёра. `wsb_live_…` — боевой, `wsb_test_…` — тестовый.

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: Уникальный ключ запроса. Повтор с тем же ключом вернёт тот же заказ без повторного списания.
      schema:
        type: string
        maxLength: 64
      example: 3f1c9a52-7d4e-4b8a-9c21-6e0f5b7a8d13
    Cursor:
      name: cursor
      in: query
      description: Курсор следующей страницы (`next_cursor` из предыдущего ответа).
      schema:
        type: string
      example: ord_8KQ1
    Limit:
      name: limit
      in: query
      description: Количество записей на странице.
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 20
    WebhookSignature:
      name: X-Wasabi-Signature
      in: header
      required: true
      description: 'HMAC-SHA256 подпись: `t={unix_time},v1={hex(hmac_sha256(secret, t + "." + raw_body))}`.'
      schema:
        type: string
      example: t=1764763504,v1=5f8a3c0d2b9e47a1c6f3e8d0b5a7294c1e6f8a3d0b2c9e47a15f8a3c0d2be91b

  schemas:
    Category:
      type: string
      description: |
        Категория товара:
        - `ai` — нейросети
        - `music` — музыка
        - `games` — игры
        - `topup` — пополнения
        - `telegram` — Telegram
        - `study` — учёба
      enum: [ai, music, games, topup, telegram, study]

    ProductType:
      type: string
      description: |
        Как выдаётся товар:
        - `account` — данные аккаунта (логин и пароль)
        - `code` — код активации
        - `topup` — пополнение на указанный логин
      enum: [account, code, topup]

    ProductField:
      type: object
      description: Поле, которое нужно передать в `fields` при заказе.
      required: [name, label, type, required]
      properties:
        name:
          type: string
          description: Ключ в объекте `fields`.
          example: login
        label:
          type: string
          description: Название поля для показа покупателю.
          example: Логин Steam
        type:
          type: string
          enum: [string, email, phone]
          example: string
        required:
          type: boolean
          example: true
        enum:
          type: array
          description: Допустимые значения, если список ограничен.
          items:
            type: string
          example: [RU, KZ, CIS]

    Product:
      type: object
      required: [id, name, category, type, price, currency, in_stock, fields]
      properties:
        id:
          type: string
          description: Идентификатор товара.
          example: chatgpt-plus-1m
        name:
          type: string
          example: ChatGPT Plus — 1 месяц
        category:
          $ref: "#/components/schemas/Category"
        type:
          $ref: "#/components/schemas/ProductType"
        price:
          type: [number, "null"]
          description: Цена для партнёра в рублях. `null` для пополнений — итог считается от `amount` с учётом `fee_percent`.
          example: 1990
        currency:
          type: string
          const: RUB
          example: RUB
        min_amount:
          type: number
          description: Только для `topup` — минимальная сумма пополнения.
          example: 100
        max_amount:
          type: number
          description: Только для `topup` — максимальная сумма пополнения.
          example: 50000
        fee_percent:
          type: number
          description: Только для `topup` — комиссия в процентах от суммы.
          example: 6
        in_stock:
          type: boolean
          description: Есть ли товар в наличии прямо сейчас.
          example: true
        fields:
          type: array
          description: Какие данные нужны для заказа (email, логин, регион…).
          items:
            $ref: "#/components/schemas/ProductField"

    CreateOrderRequest:
      type: object
      required: [product]
      properties:
        product:
          type: string
          description: ID товара.
          example: steam-topup
        qty:
          type: integer
          minimum: 1
          maximum: 50
          default: 1
          description: Количество. Для пополнений всегда 1.
          example: 1
        amount:
          type: number
          description: Сумма пополнения в рублях. Обязательна для товаров типа `topup`.
          example: 1000
        fields:
          type: object
          description: Данные для выдачи — ключи из `Product.fields`.
          additionalProperties:
            type: string
          example:
            login: player_one
        external_id:
          type: string
          maxLength: 128
          description: Ваш идентификатор заказа — вернётся в ответе и вебхуках.
          example: shop-10483

    OrderStatus:
      type: string
      description: |
        - `processing` — сумма удержана, товар выдаётся
        - `delivered` — товар выдан
        - `failed` — выдача не удалась
        - `refunded` — средства возвращены на баланс
      enum: [processing, delivered, failed, refunded]

    OrderItem:
      type: object
      description: Выданный товар. Набор полей зависит от `type`.
      required: [type]
      properties:
        type:
          $ref: "#/components/schemas/ProductType"
        code:
          type: string
          description: Код активации (`code`).
          example: SPOT-7QH4-K9XM-2LPA
        login:
          type: string
          description: Логин аккаунта (`account`) или аккаунт, который пополнен (`topup`).
          example: anna@example.com
        password:
          type: string
          description: Пароль аккаунта (`account`).
          example: Wq7!rP2m-x9L
        amount:
          type: number
          description: Зачисленная сумма (`topup`).
          example: 1000
        currency:
          type: string
          example: RUB
        expires_at:
          type: [string, "null"]
          format: date-time
          description: Когда истекает подписка или код.
          example: "2027-01-03T12:00:00Z"
        instructions:
          type: string
          description: Инструкция для покупателя.
          example: Войдите на chatgpt.com с этими данными и смените пароль.

    Order:
      type: object
      required: [id, status, product, qty, charged, currency, balance, created_at]
      properties:
        id:
          type: string
          example: ord_8KQ2
        status:
          $ref: "#/components/schemas/OrderStatus"
        product:
          type: string
          example: chatgpt-plus-1m
        qty:
          type: integer
          example: 1
        amount:
          type: number
          description: Сумма пополнения (для `topup`).
          example: 1000
        external_id:
          type: [string, "null"]
          example: shop-10482
        charged:
          type: number
          description: Списано с баланса, ₽.
          example: 1990
        currency:
          type: string
          example: RUB
        balance:
          type: number
          description: Баланс партнёра после операции, ₽.
          example: 86400
        item:
          description: Выданный товар. `null`, пока заказ не выдан.
          oneOf:
            - $ref: "#/components/schemas/OrderItem"
            - type: "null"
        failure:
          type: object
          description: Причина неудачи (для `failed` и `refunded`).
          properties:
            code:
              type: string
              example: account_not_found
            message:
              type: string
              example: Аккаунт Steam с логином player_two не найден.
        created_at:
          type: string
          format: date-time
          example: "2026-12-03T12:00:00Z"
        delivered_at:
          type: string
          format: date-time
          example: "2026-12-03T12:00:02Z"

    Balance:
      type: object
      required: [balance, currency, held]
      properties:
        balance:
          type: number
          description: Доступно для заказов, ₽.
          example: 85340
        currency:
          type: string
          example: RUB
        held:
          type: number
          description: Удержано под заказы в обработке, ₽.
          example: 530
        updated_at:
          type: string
          format: date-time
          example: "2026-12-03T12:05:04Z"

    TransactionType:
      type: string
      description: |
        - `topup` — пополнение баланса
        - `charge` — списание за заказ
        - `refund` — возврат за невыполненный заказ
      enum: [topup, charge, refund]

    Transaction:
      type: object
      required: [id, type, amount, currency, balance_after, created_at]
      properties:
        id:
          type: string
          example: txn_5Hd2
        type:
          $ref: "#/components/schemas/TransactionType"
        amount:
          type: number
          description: Сумма операции, ₽. Списания отрицательные.
          example: -1060
        currency:
          type: string
          example: RUB
        balance_after:
          type: number
          example: 85340
        order_id:
          type: [string, "null"]
          example: ord_8KQ3
        description:
          type: string
          example: Пополнение Steam — 1000 ₽
        created_at:
          type: string
          format: date-time
          example: "2026-12-03T12:05:00Z"

    OrderEvent:
      type: object
      required: [event, created_at, data]
      properties:
        event:
          type: string
          enum: [order.delivered, order.processing, order.failed]
          example: order.delivered
        created_at:
          type: string
          format: date-time
          example: "2026-12-03T12:05:04Z"
        data:
          $ref: "#/components/schemas/Order"

    BalanceTopupEvent:
      type: object
      required: [event, created_at, data]
      properties:
        event:
          type: string
          const: balance.topup
        created_at:
          type: string
          format: date-time
          example: "2026-12-02T09:30:00Z"
        data:
          $ref: "#/components/schemas/Transaction"

    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message]
          properties:
            code:
              type: string
              description: Машиночитаемый код ошибки.
              example: insufficient_balance
            message:
              type: string
              description: Описание ошибки для разработчика.
              example: Недостаточно средств на балансе.

  responses:
    BadRequest:
      description: Некорректный запрос — не хватает или неверно заполнены поля.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: invalid_fields
              message: "Поле fields.login обязательно для товара steam-topup."
    Unauthorized:
      description: Ключ не передан, отозван или неверен.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: unauthorized
              message: Неверный или отозванный API-ключ.
    InsufficientBalance:
      description: На балансе недостаточно средств для заказа.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: insufficient_balance
              message: "Недостаточно средств: нужно 1060 ₽, доступно 420 ₽."
    NotFound:
      description: Ресурс не найден.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: not_found
              message: Товар netflix-premium-12m не найден.
    IdempotencyConflict:
      description: Ключ идемпотентности уже использован с другим телом запроса.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: idempotency_conflict
              message: Idempotency-Key уже использован для другого запроса.
    RateLimited:
      description: Превышен лимит запросов. Повторите после `Retry-After` секунд.
      headers:
        Retry-After:
          description: Через сколько секунд можно повторить запрос.
          schema:
            type: integer
          example: 2
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: rate_limited
              message: Слишком много запросов. Лимит — 60 в минуту.
