{
  "openapi": "3.1.0",
  "info": {
    "title": "GMT Partner API",
    "version": "1.0.0",
    "description": "Партнёрский API продажи Telegram-аккаунтов за баланс GMT."
  },
  "servers": [
    {"url": "https://gmt.x4n.pw/api/v1", "description": "Production"}
  ],
  "security": [{"bearerAuth": []}],
  "paths": {
    "/me": {
      "get": {
        "summary": "Профиль и баланс партнёра",
        "operationId": "getPartner",
        "responses": {
          "200": {
            "description": "Данные партнёра",
            "content": {"application/json": {"schema": {"$ref": "#/components/schemas/MeResponse"}}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"}
        }
      }
    },
    "/recommendations": {
      "get": {
        "summary": "Обязательное условие о видеозаписи перед покупкой",
        "operationId": "getRecommendations",
        "responses": {
          "200": {
            "description": "Версия и короткий текст условия покупки",
            "content": {"application/json": {"schema": {"$ref": "#/components/schemas/RecommendationsResponse"}}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"}
        }
      }
    },
    "/products": {
      "get": {
        "summary": "Актуальный каталог",
        "operationId": "listProducts",
        "responses": {
          "200": {
            "description": "Список доступных товаров",
            "content": {"application/json": {"schema": {
              "type": "object",
              "required": ["success", "data"],
              "properties": {
                "success": {"type": "boolean", "const": true},
                "data": {"type": "array", "items": {"$ref": "#/components/schemas/Product"}}
              }
            }}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"}
        }
      }
    },
    "/products/{product_id}": {
      "get": {
        "summary": "Один товар",
        "operationId": "getProduct",
        "parameters": [{"$ref": "#/components/parameters/ProductId"}],
        "responses": {
          "200": {
            "description": "Товар",
            "content": {"application/json": {"schema": {
              "type": "object",
              "required": ["success", "data"],
              "properties": {
                "success": {"type": "boolean", "const": true},
                "data": {"$ref": "#/components/schemas/Product"}
              }
            }}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"},
          "404": {"$ref": "#/components/responses/NotFound"}
        }
      }
    },
    "/orders": {
      "post": {
        "summary": "Создать и оплатить заказ",
        "operationId": "createOrder",
        "parameters": [{"$ref": "#/components/parameters/IdempotencyKey"}],
        "requestBody": {
          "required": true,
          "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CreateOrderRequest"}}}
        },
        "responses": {
          "200": {
            "description": "Повтор идемпотентного запроса; возвращён существующий заказ",
            "content": {"application/json": {"schema": {"$ref": "#/components/schemas/OrderResponse"}}}
          },
          "202": {
            "description": "Новый заказ принят",
            "content": {"application/json": {"schema": {"$ref": "#/components/schemas/OrderResponse"}}}
          },
          "400": {"$ref": "#/components/responses/BadRequest"},
          "401": {"$ref": "#/components/responses/Unauthorized"},
          "402": {"$ref": "#/components/responses/InsufficientBalance"},
          "409": {"$ref": "#/components/responses/Conflict"}
        }
      },
      "get": {
        "summary": "Список заказов",
        "operationId": "listOrders",
        "parameters": [
          {"$ref": "#/components/parameters/Limit"},
          {"$ref": "#/components/parameters/Offset"}
        ],
        "responses": {
          "200": {
            "description": "Страница заказов",
            "content": {"application/json": {"schema": {
              "type": "object",
              "required": ["success", "data", "pagination"],
              "properties": {
                "success": {"type": "boolean", "const": true},
                "data": {"type": "array", "items": {"$ref": "#/components/schemas/Order"}},
                "pagination": {"$ref": "#/components/schemas/Pagination"}
              }
            }}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"}
        }
      }
    },
    "/orders/{order_id}": {
      "get": {
        "summary": "Состояние заказа",
        "operationId": "getOrder",
        "parameters": [{"$ref": "#/components/parameters/OrderId"}],
        "responses": {
          "200": {
            "description": "Заказ",
            "content": {"application/json": {"schema": {"$ref": "#/components/schemas/OrderResponse"}}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"},
          "404": {"$ref": "#/components/responses/NotFound"}
        }
      }
    },
    "/orders/{order_id}/download": {
      "get": {
        "summary": "Скачать ZIP готового заказа",
        "operationId": "downloadOrder",
        "parameters": [{"$ref": "#/components/parameters/OrderId"}],
        "responses": {
          "200": {
            "description": "ZIP-файл",
            "content": {"application/zip": {"schema": {"type": "string", "contentEncoding": "binary"}}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"},
          "404": {"$ref": "#/components/responses/NotFound"},
          "409": {"$ref": "#/components/responses/Conflict"},
          "410": {"$ref": "#/components/responses/FileUnavailable"}
        }
      }
    },
    "/orders/{order_id}/phonecode": {
      "post": {
        "summary": "Запросить повторный код авторизации",
        "operationId": "reissuePhonecode",
        "parameters": [{"$ref": "#/components/parameters/OrderId"}],
        "responses": {
          "202": {
            "description": "Запрос повторного кода принят",
            "content": {"application/json": {"schema": {
              "type": "object",
              "required": ["success", "data"],
              "properties": {
                "success": {"type": "boolean", "const": true},
                "data": {
                  "type": "object",
                  "required": ["order_id", "status"],
                  "properties": {
                    "order_id": {"type": "integer"},
                    "status": {"type": "string", "const": "waiting"}
                  }
                }
              }
            }}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"},
          "404": {"$ref": "#/components/responses/NotFound"},
          "409": {"$ref": "#/components/responses/Conflict"},
          "502": {"description": "Поставщик не смог запустить повторную выдачу"}
        }
      }
    },
    "/transactions": {
      "get": {
        "summary": "История операций баланса",
        "operationId": "listTransactions",
        "parameters": [
          {"$ref": "#/components/parameters/Limit"},
          {"$ref": "#/components/parameters/Offset"}
        ],
        "responses": {
          "200": {
            "description": "Страница операций",
            "content": {"application/json": {"schema": {
              "type": "object",
              "required": ["success", "data", "pagination"],
              "properties": {
                "success": {"type": "boolean", "const": true},
                "data": {"type": "array", "items": {"$ref": "#/components/schemas/Transaction"}},
                "pagination": {"$ref": "#/components/schemas/Pagination"}
              }
            }}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"}
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "GMT API key",
        "description": "Ключ вида gmt_live_..., созданный в боте GMT."
      }
    },
    "parameters": {
      "ProductId": {
        "name": "product_id", "in": "path", "required": true,
        "schema": {"type": "integer", "minimum": 1}
      },
      "OrderId": {
        "name": "order_id", "in": "path", "required": true,
        "schema": {"type": "integer", "minimum": 1}
      },
      "IdempotencyKey": {
        "name": "Idempotency-Key", "in": "header", "required": true,
        "description": "Новый уникальный ключ для каждой логической покупки. При повторе запроса используйте тот же ключ.",
        "schema": {"type": "string", "minLength": 1, "maxLength": 150}
      },
      "Limit": {
        "name": "limit", "in": "query", "required": false,
        "schema": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20}
      },
      "Offset": {
        "name": "offset", "in": "query", "required": false,
        "schema": {"type": "integer", "minimum": 0, "default": 0}
      }
    },
    "schemas": {
      "MeResponse": {
        "type": "object",
        "required": ["success", "data"],
        "properties": {
          "success": {"type": "boolean", "const": true},
          "data": {
            "type": "object",
            "required": ["telegram_id", "balance_rub", "currency"],
            "properties": {
              "telegram_id": {"type": "integer"},
              "balance_rub": {"type": "number"},
              "currency": {"type": "string", "const": "RUB"}
            }
          }
        }
      },
      "RecommendationsResponse": {
        "type": "object",
        "required": ["success", "data"],
        "properties": {
          "success": {"type": "boolean", "const": true},
          "data": {
            "type": "object",
            "required": ["version", "text"],
            "properties": {
              "version": {"type": "string"},
              "text": {"type": "string"}
            }
          }
        }
      },
      "Product": {
        "type": "object",
        "required": ["id", "name", "description", "country_code", "country", "stock", "price_rub", "formats"],
        "properties": {
          "id": {"type": "integer"},
          "name": {"type": "string"},
          "description": {"type": "string"},
          "country_code": {"type": "string"},
          "country": {"type": "string"},
          "stock": {"type": "integer", "minimum": 0},
          "price_rub": {"type": "number", "minimum": 0},
          "formats": {
            "type": "array",
            "items": {"type": "string", "enum": ["tdata", "sessionjson", "phonecode"]}
          }
        }
      },
      "CreateOrderRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": ["product_id", "format", "recommendations_accepted"],
        "properties": {
          "product_id": {"type": "integer", "minimum": 1},
          "format": {"type": "string", "enum": ["tdata", "sessionjson", "phonecode"]},
          "quantity": {"type": "integer", "minimum": 1, "maximum": 100, "default": 1},
          "external_order_id": {"type": "string", "maxLength": 150},
          "recommendations_accepted": {"type": "boolean", "const": true}
        }
      },
      "Order": {
        "type": "object",
        "required": ["id", "status", "product", "format", "quantity", "amount_rub"],
        "properties": {
          "id": {"type": "integer"},
          "external_order_id": {"type": ["string", "null"]},
          "status": {"type": "string", "enum": ["processing", "completed", "failed", "refunded", "cancelled"]},
          "product": {
            "type": "object",
            "required": ["id", "name"],
            "properties": {"id": {"type": "integer"}, "name": {"type": "string"}}
          },
          "format": {"type": "string", "enum": ["tdata", "sessionjson", "phonecode"]},
          "quantity": {"type": "integer"},
          "amount_rub": {"type": "number"},
          "created_at": {"type": ["string", "null"]},
          "completed_at": {"type": ["string", "null"]},
          "download_url": {"type": "string"},
          "delivery": {"$ref": "#/components/schemas/Delivery"},
          "error": {"$ref": "#/components/schemas/ErrorDetail"},
          "phonecode_reissue_status": {"type": "string", "enum": ["starting", "waiting", "completed", "failed"]},
          "phonecode_reissue_error": {"type": "string", "description": "Понятное описание причины при status=failed"}
        }
      },
      "OrderResponse": {
        "type": "object",
        "required": ["success", "data"],
        "properties": {
          "success": {"type": "boolean", "const": true},
          "data": {"$ref": "#/components/schemas/Order"}
        }
      },
      "Delivery": {
        "type": "object",
        "properties": {
          "phone": {"type": ["string", "null"]},
          "code": {"type": ["string", "null"]},
          "twofa_password": {"type": ["string", "null"]}
        }
      },
      "Transaction": {
        "type": "object",
        "required": ["id", "amount", "operation_type", "created_at"],
        "properties": {
          "id": {"type": "integer"},
          "amount": {"type": "number"},
          "operation_type": {"type": "string"},
          "reason": {"type": ["string", "null"]},
          "order_id": {"type": ["integer", "null"]},
          "created_at": {"type": "string"}
        }
      },
      "Pagination": {
        "type": "object",
        "required": ["limit", "offset"],
        "properties": {
          "limit": {"type": "integer"},
          "offset": {"type": "integer"}
        }
      },
      "ErrorDetail": {
        "type": "object",
        "required": ["code", "message"],
        "properties": {
          "code": {"type": "string"},
          "message": {"type": "string"}
        }
      },
      "ErrorResponse": {
        "type": "object",
        "required": ["success", "error", "request_id"],
        "properties": {
          "success": {"type": "boolean", "const": false},
          "error": {"$ref": "#/components/schemas/ErrorDetail"},
          "request_id": {"type": "string"}
        }
      }
    },
    "responses": {
      "BadRequest": {
        "description": "Некорректный запрос",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}
      },
      "Unauthorized": {
        "description": "Нет действующего API-ключа",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}
      },
      "InsufficientBalance": {
        "description": "Недостаточно средств",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}
      },
      "NotFound": {
        "description": "Объект не найден",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}
      },
      "Conflict": {
        "description": "Конфликт состояния или уникального идентификатора",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}
      },
      "FileUnavailable": {
        "description": "Файл недоступен",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}
      }
    }
  }
}
