{
  "openapi": "3.0.3",
  "info": {
    "title": "eSIM Agents API",
    "description": "Wholesale eSIM provisioning API for agents and partners.",
    "version": "1.0.0",
    "contact": {
      "url": "https://esim.agents.co.th"
    }
  },
  "servers": [
    {
      "url": "https://esim.agents.co.th/api/v1",
      "description": "Production"
    }
  ],
  "security": [
    { "ApiKeyAuth": [] }
  ],
  "components": {
    "securitySchemes": {
      "ApiKeyAuth": {
        "type": "apiKey",
        "in": "header",
        "name": "x-api-key"
      }
    },
    "schemas": {
      "ErrorResponse": {
        "type": "object",
        "properties": {
          "success": { "type": "boolean", "example": false },
          "error": {
            "type": "object",
            "properties": {
              "code": { "type": "string", "example": "FORBIDDEN_SCOPE" },
              "message": { "type": "string", "example": "Missing required scope: orders:write" }
            },
            "required": ["code", "message"]
          }
        },
        "required": ["success", "error"]
      },
      "Balance": {
        "type": "object",
        "properties": {
          "accountId": { "type": "string", "format": "uuid" },
          "totalTopupsThb": { "type": "number" },
          "totalPurchasesThb": { "type": "number" },
          "balanceThb": { "type": "number" }
        },
        "required": ["accountId", "totalTopupsThb", "totalPurchasesThb", "balanceThb"]
      },
      "Product": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "name": { "type": "string" },
          "description": { "type": "string" },
          "provider": { "type": "string" },
          "sku": { "type": "string" },
          "retailPriceThb": { "type": "number", "nullable": true },
          "metadata": {},
          "promotionLabel": { "type": "string", "nullable": true },
          "promotionFeatures": { "type": "array", "items": { "type": "string" } },
          "currentUnitPriceThb": { "type": "number" },
          "activeTierMinTrailingYearQty": { "type": "integer" }
        },
        "required": ["id", "name", "description", "provider", "sku", "currentUnitPriceThb", "activeTierMinTrailingYearQty"]
      },
      "Payment": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "merchantOrderId": { "type": "string" },
          "amountThb": { "type": "number" },
          "baseAmountThb": { "type": "number" },
          "processingFeeThb": { "type": "number" },
          "vatThb": { "type": "number" },
          "walletCreditThb": { "type": "number" },
          "status": { "type": "string" },
          "paymentMethod": {
            "type": "string",
            "enum": ["promptpay", "card", "airpay", "alipay", "linepay", "truemoney", "wechat", "kplus", "scb_easy", "bbl_deeplink", "baybank_deeplink"]
          },
          "paidAt": { "type": "string", "format": "date-time", "nullable": true },
          "createdAt": { "type": "string", "format": "date-time" }
        },
        "required": ["id", "merchantOrderId", "amountThb", "baseAmountThb", "processingFeeThb", "vatThb", "walletCreditThb", "status", "paymentMethod", "createdAt"]
      },
      "EsimItem": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "sequenceNo": { "type": "integer" },
          "status": { "type": "string", "example": "provisioned" },
          "provider": { "type": "string", "nullable": true },
          "iccid": { "type": "string", "nullable": true },
          "phone": { "type": "string", "nullable": true },
          "activationCode": { "type": "string", "nullable": true },
          "smdpAddress": { "type": "string", "nullable": true },
          "qrCode": { "type": "string", "nullable": true },
          "qrBase64Url": { "type": "string", "nullable": true, "description": "Only present when includeQrImages=true" }
        },
        "required": ["id", "sequenceNo", "status"]
      },
      "CreateOrderEsimItem": {
        "type": "object",
        "properties": {
          "sequenceNo": { "type": "integer" },
          "status": { "type": "string", "example": "provisioned" },
          "provider": { "type": "string" },
          "iccid": { "type": "string" },
          "phone": { "type": "string", "nullable": true },
          "activationCode": { "type": "string" },
          "smdpAddress": { "type": "string" },
          "qrCode": { "type": "string" },
          "qrBase64Url": { "type": "string", "nullable": true, "description": "Only present when includeQrImages=true" }
        },
        "required": ["sequenceNo", "status", "provider", "iccid", "activationCode", "smdpAddress", "qrCode"]
      },
      "ProductSummary": {
        "type": "object",
        "properties": {
          "name": { "type": "string" },
          "sku": { "type": "string" }
        },
        "required": ["name", "sku"]
      },
      "Order": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "status": { "type": "string" },
          "orderSource": { "type": "string", "enum": ["web", "api"] },
          "quantity": { "type": "integer" },
          "unitPriceThb": { "type": "number" },
          "totalPriceThb": { "type": "number" },
          "createdAt": { "type": "string", "format": "date-time" },
          "product": { "$ref": "#/components/schemas/ProductSummary" },
          "items": { "type": "array", "items": { "$ref": "#/components/schemas/EsimItem" } }
        },
        "required": ["id", "status", "orderSource", "quantity", "unitPriceThb", "totalPriceThb", "createdAt", "product", "items"]
      },
      "CreateOrderResponse": {
        "type": "object",
        "properties": {
          "purchaseOrderId": { "type": "string", "format": "uuid" },
          "reused": { "type": "boolean" },
          "unitPriceThb": { "type": "number" },
          "totalPriceThb": { "type": "number" },
          "quantity": { "type": "integer" },
          "items": { "type": "array", "items": { "$ref": "#/components/schemas/CreateOrderEsimItem" } }
        },
        "required": ["purchaseOrderId", "reused"]
      }
    }
  },
  "paths": {
    "/getBalance": {
      "get": {
        "operationId": "getBalance",
        "summary": "Get account balance",
        "description": "Returns account balance summary including total topups, total purchases, and current available balance.",
        "tags": ["Account"],
        "security": [{ "ApiKeyAuth": [] }],
        "responses": {
          "200": {
            "description": "Balance retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": { "type": "boolean", "example": true },
                    "data": { "$ref": "#/components/schemas/Balance" }
                  }
                }
              }
            }
          },
          "401": { "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "403": { "description": "Forbidden / KYC required", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      }
    },
    "/getProducts": {
      "get": {
        "operationId": "getProducts",
        "summary": "List products",
        "description": "Returns active products with account-specific tier pricing. Use the product id as the productId when creating orders.",
        "tags": ["Products"],
        "security": [{ "ApiKeyAuth": [] }],
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": { "type": "integer", "minimum": 1, "maximum": 200, "default": 50 },
            "description": "Number of products to return"
          }
        ],
        "responses": {
          "200": {
            "description": "Products list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": { "type": "boolean", "example": true },
                    "data": { "type": "array", "items": { "$ref": "#/components/schemas/Product" } }
                  }
                }
              }
            }
          },
          "401": { "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "403": { "description": "Forbidden / KYC required", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      }
    },
    "/getPaymentHistory": {
      "get": {
        "operationId": "getPaymentHistory",
        "summary": "List payment history",
        "description": "Returns wallet topup and payment history including amount breakdown, method, status, and timestamps.",
        "tags": ["Payments"],
        "security": [{ "ApiKeyAuth": [] }],
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": { "type": "integer", "minimum": 1, "maximum": 200, "default": 50 },
            "description": "Number of records to return"
          }
        ],
        "responses": {
          "200": {
            "description": "Payment history",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": { "type": "boolean", "example": true },
                    "data": { "type": "array", "items": { "$ref": "#/components/schemas/Payment" } }
                  }
                }
              }
            }
          },
          "401": { "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "403": { "description": "Forbidden / KYC required", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      }
    },
    "/createOrder": {
      "post": {
        "operationId": "createOrder",
        "summary": "Create eSIM order",
        "description": "Creates a wholesale eSIM purchase order. eSIMs are provisioned immediately and returned in the response. Supports idempotency. Resubmitting the same idempotencyKey returns the original order without charging twice.",
        "tags": ["Orders"],
        "security": [{ "ApiKeyAuth": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "productId": { "type": "string", "format": "uuid", "description": "Product ID from /getProducts" },
                  "quantity": { "type": "integer", "minimum": 1, "maximum": 2000, "description": "Number of eSIMs to purchase" },
                  "idempotencyKey": { "type": "string", "minLength": 8, "maxLength": 120, "description": "Unique key to prevent duplicate orders on retry" },
                  "includeQrImages": { "type": "boolean", "default": false, "description": "Include base64-encoded QR images per eSIM in the response" }
                },
                "required": ["productId", "quantity"]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Order created with provisioned eSIMs",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": { "type": "boolean", "example": true },
                    "data": { "$ref": "#/components/schemas/CreateOrderResponse" }
                  }
                }
              }
            }
          },
          "400": { "description": "Invalid request body", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "401": { "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "403": { "description": "Forbidden / KYC required", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "409": { "description": "eSIM inventory empty or card data incomplete", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      }
    },
    "/getOrderStatus": {
      "get": {
        "operationId": "getOrderStatus",
        "summary": "Get single order",
        "description": "Returns a single purchase order with full eSIM details for each item.",
        "tags": ["Orders"],
        "security": [{ "ApiKeyAuth": [] }],
        "parameters": [
          {
            "name": "purchaseOrderId",
            "in": "query",
            "required": true,
            "schema": { "type": "string", "format": "uuid" },
            "description": "The order ID to look up"
          },
          {
            "name": "includeQrImages",
            "in": "query",
            "required": false,
            "schema": { "type": "string", "enum": ["true", "false"], "default": "false" },
            "description": "Include base64-encoded QR images per eSIM"
          }
        ],
        "responses": {
          "200": {
            "description": "Order with items",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": { "type": "boolean", "example": true },
                    "data": { "$ref": "#/components/schemas/Order" }
                  }
                }
              }
            }
          },
          "400": { "description": "Invalid query parameters", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "401": { "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "403": { "description": "Forbidden / KYC required", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "404": { "description": "Order not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      }
    },
    "/getOrders": {
      "get": {
        "operationId": "getOrders",
        "summary": "List orders",
        "description": "Returns a list of all purchase orders with their eSIM items. Each order includes product info, pricing, and provisioned eSIM details.",
        "tags": ["Orders"],
        "security": [{ "ApiKeyAuth": [] }],
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": { "type": "integer", "minimum": 1, "maximum": 200, "default": 50 },
            "description": "Number of orders to return"
          },
          {
            "name": "includeQrImages",
            "in": "query",
            "required": false,
            "schema": { "type": "string", "enum": ["true", "false"], "default": "false" },
            "description": "Include base64-encoded QR images per eSIM"
          }
        ],
        "responses": {
          "200": {
            "description": "Orders list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": { "type": "boolean", "example": true },
                    "data": { "type": "array", "items": { "$ref": "#/components/schemas/Order" } }
                  }
                }
              }
            }
          },
          "401": { "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "403": { "description": "Forbidden / KYC required", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      }
    }
  }
}
