{
  "openapi": "3.0.3",
  "info": {
    "title": "BRC Core API",
    "description": "API para parceiros: depósito BRL, endereço Liquid descartável para depósito BRC on-chain (terceiros), cotação, conversão BRC (mint), resgate (burn), saldos e transações. Autenticação via header X-API-Key.",
    "version": "1.0.0",
    "contact": {
      "email": "contato@brctoken.xyz"
    }
  },
  "servers": [
    {
      "url": "https://api.brctoken.xyz",
      "description": "Produção"
    }
  ],
  "security": [
    {
      "ApiKeyAuth": []
    }
  ],
  "paths": {
    "/v1/deposit": {
      "post": {
        "tags": ["ledger"],
        "summary": "Pedir depósito BRL (pendente até confirmação)",
        "security": [{ "ApiKeyAuth": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/DepositRequest" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Depósito criado (pendente)",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/DepositResponse" }
              }
            }
          },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" }
        }
      }
    },
    "/v1/brc-deposit-addresses": {
      "post": {
        "tags": ["ledger"],
        "summary": "Gerar endereço Liquid descartável para depósito BRC (por transação)",
        "description": "Cria um intent com endereço único para receber BRC na Liquid. Após confirmação on-chain, o saldo é creditado no ledger BRC do parceiro e o token é destruído (burn) na custódia. Requer feature `flow_brc_deposit_address`. Corpo opcional: `external_id` (até 128 caracteres, único por parceiro) e `metadata` (objeto JSON).",
        "security": [{ "ApiKeyAuth": [] }],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/BrcDepositAddressCreateRequest" }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Intent criado; aguardando fundos on-chain",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/BrcDepositAddressCreateResponse" }
              }
            }
          },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "409": { "$ref": "#/components/responses/Conflict" }
        }
      }
    },
    "/v1/brc-deposit-addresses/{intent_id}": {
      "get": {
        "tags": ["ledger"],
        "summary": "Consultar status do depósito BRC por intent_id",
        "description": "Devolve estado do intent (`awaiting_funds`, `processing`, `credited`, `expired`). Com `credited`, inclui montante e txids de receção e sweep (burn).",
        "security": [{ "ApiKeyAuth": [] }],
        "parameters": [
          {
            "name": "intent_id",
            "in": "path",
            "required": true,
            "description": "UUID retornado em POST /v1/brc-deposit-addresses",
            "schema": { "type": "string", "format": "uuid" }
          }
        ],
        "responses": {
          "200": {
            "description": "Estado atual do intent",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/BrcDepositAddressGetResponse" }
              }
            }
          },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/v1/quote": {
      "get": {
        "tags": ["ledger"],
        "summary": "Cotação BRL → BRC",
        "security": [{ "ApiKeyAuth": [] }],
        "parameters": [
          {
            "name": "brl_amount",
            "in": "query",
            "required": true,
            "description": "Valor BRL",
            "schema": { "type": "string", "example": "1000" }
          }
        ],
        "responses": {
          "200": {
            "description": "Cotação válida por 2 minutos",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/QuoteResponse" }
              }
            }
          },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" }
        }
      }
    },
    "/v1/convert": {
      "post": {
        "tags": ["ledger"],
        "summary": "Converter BRL em BRC (mint)",
        "security": [{ "ApiKeyAuth": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/ConvertRequest" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Conversão confirmada",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ConvertResponse" }
              }
            }
          },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "502": { "$ref": "#/components/responses/BadGateway" }
        }
      }
    },
    "/v1/withdraw": {
      "post": {
        "tags": ["ledger"],
        "summary": "Resgatar BRC (burn) e receber BRL via PIX",
        "security": [{ "ApiKeyAuth": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/WithdrawRequest" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Resgate confirmado",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/WithdrawResponse" }
              }
            }
          },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "502": { "$ref": "#/components/responses/BadGateway" }
        }
      }
    },
    "/v1/balance": {
      "get": {
        "tags": ["ledger"],
        "summary": "Saldos BRL e BRC (ledger)",
        "security": [{ "ApiKeyAuth": [] }],
        "responses": {
          "200": {
            "description": "Saldos do parceiro",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/BalanceResponse" }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" }
        }
      }
    },
    "/v1/me": {
      "get": {
        "tags": ["ledger"],
        "summary": "Perfil do parceiro",
        "security": [{ "ApiKeyAuth": [] }],
        "responses": {
          "200": {
            "description": "Dados do parceiro autenticado",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/PartnerMeResponse" }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" }
        }
      }
    },
    "/v1/transactions": {
      "get": {
        "tags": ["ledger"],
        "summary": "Listar transações do parceiro",
        "security": [{ "ApiKeyAuth": [] }],
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "description": "Máximo de itens (default 50, máx 200)",
            "schema": { "type": "integer", "default": 50 }
          },
          {
            "name": "offset",
            "in": "query",
            "description": "Offset para paginação",
            "schema": { "type": "integer", "default": 0 }
          }
        ],
        "responses": {
          "200": {
            "description": "Lista de transações",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/TransactionsListResponse" }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" }
        }
      }
    },
    "/v1/health": {
      "get": {
        "tags": ["sistema"],
        "summary": "Estado da API e do elementsd",
        "security": [],
        "responses": {
          "200": {
            "description": "API saudável",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/HealthOKResponse" }
              }
            }
          },
          "503": {
            "description": "elementsd indisponível",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/HealthDegradedResponse" }
              }
            }
          }
        }
      }
    },
    "/v1/asset-info": {
      "get": {
        "tags": ["brc"],
        "summary": "Metadados do asset BRC e do nó",
        "security": [],
        "responses": {
          "200": {
            "description": "Info do asset",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/AssetInfoResponse" }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "ApiKeyAuth": {
        "type": "apiKey",
        "in": "header",
        "name": "X-API-Key",
        "description": "API key do parceiro (formato brc_live_…)"
      }
    },
    "schemas": {
      "DepositRequest": {
        "type": "object",
        "required": ["amount", "railway"],
        "properties": {
          "amount": { "type": "number", "example": 1000 },
          "railway": { "type": "string", "example": "pix" }
        }
      },
      "DepositResponse": {
        "type": "object",
        "properties": {
          "transaction_id": { "type": "string", "format": "uuid" },
          "status": { "type": "string", "example": "pending" },
          "amount": { "type": "number" },
          "railway": { "type": "string" },
          "message": { "type": "string" }
        }
      },
      "BrcDepositAddressCreateRequest": {
        "type": "object",
        "properties": {
          "external_id": { "type": "string", "maxLength": 128, "description": "Opcional; idempotência / correlação no teu sistema (único por parceiro)." },
          "metadata": { "type": "object", "additionalProperties": true, "description": "Opcional; objeto JSON livre (ex.: pedido, utilizador)." }
        }
      },
      "BrcDepositAddressCreateResponse": {
        "type": "object",
        "properties": {
          "intent_id": { "type": "string", "format": "uuid" },
          "liquid_address": { "type": "string", "description": "Endereço Liquid para enviar BRC (asset_id)" },
          "asset_id": { "type": "string", "description": "Hex do asset BRC na Liquid" },
          "status": { "type": "string", "enum": ["awaiting_funds"], "description": "Estado inicial" },
          "external_id": { "type": "string", "description": "Presente só se enviado no pedido" },
          "expires_at": { "type": "string", "format": "date-time" },
          "created_at": { "type": "string", "format": "date-time" }
        }
      },
      "BrcDepositAddressGetResponse": {
        "type": "object",
        "properties": {
          "intent_id": { "type": "string", "format": "uuid" },
          "liquid_address": { "type": "string" },
          "status": { "type": "string", "enum": ["awaiting_funds", "processing", "credited", "expired"] },
          "external_id": { "type": "string" },
          "metadata": { "type": "object", "additionalProperties": true },
          "brc_amount": { "type": "number", "description": "Quando status=credited" },
          "liquid_txid_receive": { "type": "string", "description": "Tx de entrada de BRC no endereço (quando credited)" },
          "liquid_txid_sweep": { "type": "string", "description": "Tx de burn/sweep após crédito (quando credited)" },
          "updated_at": { "type": "string", "format": "date-time" }
        }
      },
      "QuoteResponse": {
        "type": "object",
        "properties": {
          "quote_id": { "type": "string", "format": "uuid" },
          "brl_amount": { "type": "number" },
          "brc_amount": { "type": "number" },
          "fee": { "type": "number" },
          "convert_fee_pct": { "type": "number" },
          "convert_fee_fixed": { "type": "number" },
          "valid_for_seconds": { "type": "integer", "example": 120 },
          "expires_at": { "type": "string", "format": "date-time" }
        }
      },
      "ConvertRequest": {
        "type": "object",
        "required": ["quote_id", "address"],
        "properties": {
          "quote_id": { "type": "string", "format": "uuid", "example": "550e8400-e29b-41d4-a716-446655440000" },
          "address": { "type": "string", "example": "el1qq..." }
        }
      },
      "ConvertResponse": {
        "type": "object",
        "properties": {
          "transaction_id": { "type": "string", "format": "uuid" },
          "quote_id": { "type": "string" },
          "brl_debited": { "type": "number" },
          "brc_minted": { "type": "number" },
          "fee": { "type": "number" },
          "address": { "type": "string" },
          "liquid_txid": { "type": "string" },
          "brl_balance": { "type": "number" },
          "brc_issued": { "type": "number", "description": "BRC líquido na plataforma (ledger: conversões − resgates); não é saldo on-chain na custódia." },
          "brc_custody_balance": { "type": "number", "description": "BRC no endereço Liquid de custódia do parceiro (verificável on-chain)." },
          "status": { "type": "string", "example": "confirmed" }
        }
      },
      "WithdrawRequest": {
        "type": "object",
        "required": ["brc_amount"],
        "properties": {
          "brc_amount": { "type": "number", "example": 947.5 }
        }
      },
      "WithdrawResponse": {
        "type": "object",
        "properties": {
          "transaction_id": { "type": "string", "format": "uuid" },
          "brc_burned": { "type": "number" },
          "pix_amount": { "type": "number" },
          "fee": { "type": "number" },
          "liquid_txid": { "type": "string" },
          "brc_issued": { "type": "number", "description": "BRC líquido na plataforma (ledger: conversões − resgates); não é saldo on-chain na custódia." },
          "brc_custody_balance": { "type": "number", "description": "BRC no endereço Liquid de custódia do parceiro (verificável on-chain)." },
          "status": { "type": "string", "example": "confirmed" }
        }
      },
      "BalanceResponse": {
        "type": "object",
        "properties": {
          "brl_balance": { "type": "number" },
          "brc_issued": { "type": "number", "description": "BRC líquido na plataforma (ledger: conversões − resgates); não é saldo on-chain na custódia." },
          "brc_custody_balance": { "type": "number", "description": "BRC no endereço Liquid de custódia do parceiro (verificável on-chain)." }
        }
      },
      "PartnerMeResponse": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "name": { "type": "string" },
          "email": { "type": "string" },
          "status": { "type": "string" },
          "liquid_address": { "type": "string" },
          "webhook_url": { "type": "string" },
          "brl_balance": { "type": "number" },
          "brc_issued": { "type": "number", "description": "BRC líquido na plataforma (ledger: conversões − resgates); não é saldo on-chain na custódia." },
          "brc_custody_balance": { "type": "number", "description": "BRC no endereço Liquid de custódia do parceiro (verificável on-chain)." },
          "fees": { "$ref": "#/components/schemas/PartnerFees" }
        }
      },
      "PartnerFees": {
        "type": "object",
        "properties": {
          "deposit_fee_pct": { "type": "number" },
          "deposit_fee_fixed": { "type": "number" },
          "convert_fee_pct": { "type": "number" },
          "convert_fee_fixed": { "type": "number" },
          "withdraw_fee_pct": { "type": "number" },
          "withdraw_fee_fixed": { "type": "number" }
        }
      },
      "TransactionsListResponse": {
        "type": "object",
        "properties": {
          "total": { "type": "integer" },
          "limit": { "type": "integer" },
          "offset": { "type": "integer" },
          "transactions": {
            "type": "array",
            "items": { "$ref": "#/components/schemas/Transaction" }
          }
        }
      },
      "Transaction": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "type": { "type": "string", "enum": ["deposit", "convert", "withdraw"] },
          "status": { "type": "string", "enum": ["pending", "confirmed"] },
          "brl_amount": { "type": "number" },
          "brc_amount": { "type": "number" },
          "fee_amount": { "type": "number" },
          "railway": { "type": "string" },
          "liquid_address": { "type": "string" },
          "liquid_txid": { "type": "string" },
          "correlation_id": { "type": "string" },
          "provider_meta": { "type": "object", "additionalProperties": true },
          "quote_id": { "type": "string" },
          "created_at": { "type": "string", "format": "date-time" },
          "updated_at": { "type": "string", "format": "date-time" }
        }
      },
      "HealthOKResponse": {
        "type": "object",
        "properties": {
          "status": { "type": "string", "example": "ok" },
          "elements": {
            "type": "object",
            "properties": {
              "status": { "type": "string", "example": "ok" },
              "network": { "type": "string" },
              "block_height": { "type": "integer" },
              "synced": { "type": "boolean" }
            }
          }
        }
      },
      "HealthDegradedResponse": {
        "type": "object",
        "properties": {
          "status": { "type": "string", "example": "degraded" },
          "elements": {
            "type": "object",
            "properties": {
              "status": { "type": "string", "example": "unavailable" },
              "error": { "type": "string" }
            }
          }
        }
      },
      "AssetInfoResponse": {
        "type": "object",
        "properties": {
          "asset_id": { "type": "string" },
          "reissuance_token": { "type": "string" },
          "network": { "type": "string" },
          "node_version": { "type": "string" },
          "node_block_height": { "type": "integer" }
        }
      },
      "ErrorEnvelope": {
        "type": "object",
        "properties": {
          "error": {
            "type": "object",
            "properties": {
              "code": { "type": "string" },
              "message": { "type": "string" }
            }
          }
        }
      }
    },
    "responses": {
      "BadRequest": {
        "description": "Bad Request",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }
          }
        }
      },
      "Unauthorized": {
        "description": "Unauthorized",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }
          }
        }
      },
      "Forbidden": {
        "description": "Forbidden",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }
          }
        }
      },
      "NotFound": {
        "description": "Not Found",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }
          }
        }
      },
      "Conflict": {
        "description": "Conflict (ex.: external_id duplicado)",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }
          }
        }
      },
      "BadGateway": {
        "description": "Bad Gateway",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }
          }
        }
      }
    }
  },
  "tags": [
    { "name": "ledger", "description": "Depósito BRL, endereço descartável BRC on-chain, cotação, conversão, resgate e saldos (X-API-Key)" },
    { "name": "brc", "description": "Metadados do asset no nó Elements" },
    { "name": "sistema", "description": "Saúde da API e do elementsd" }
  ]
}
