"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const error_1=require("@b/utils/error"),query_1=require("@b/utils/query"),exchange_1=__importDefault(require("@b/utils/exchange")),ccxt_1=__importDefault(require("ccxt")),console_1=require("@b/utils/console");exports.metadata={summary:"Retrieves the exchange balance for the logged-in user",description:"Fetches the exchange balance associated with the currently authenticated user.",operationId:"getExchangeBalance",tags:["Admin","Exchange","Balance"],requiresAuth:!0,responses:{200:{description:"Exchange balance retrieved successfully",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{asset:{type:"string",description:"The asset symbol"},available:{type:"number",description:"The available balance"},inOrder:{type:"number",description:"The balance locked in orders"},total:{type:"number",description:"The total balance"}}}}}}},401:query_1.unauthorizedResponse,500:query_1.serverErrorResponse},permission:"view.exchange.balance"};exports.default=async e=>{const{user:r,ctx:t}=e;if(!(null==r?void 0:r.id))throw(0,error_1.createError)({statusCode:401,message:"Unauthorized"});try{const e=await exchange_1.default.startExchange(t);if(!e)throw(0,error_1.createError)({statusCode:500,message:"Exchange or provider not available"});const r=await e.fetchBalance();return{balance:Object.entries(r.total).map(([e,t])=>({asset:e,available:r.free[e]||0,inOrder:r.used[e]||0,total:t})).filter(e=>e.available>0||e.inOrder>0)}}catch(e){if(e instanceof ccxt_1.default.AuthenticationError){console_1.logger.error("EXCHANGE",`Authentication error for userId: ${r.id}`,e);throw(0,error_1.createError)({statusCode:401,message:"Authentication error: please check your API credentials."})}if(e instanceof ccxt_1.default.NetworkError){console_1.logger.error("EXCHANGE",`Network error for userId: ${r.id}`,e);throw(0,error_1.createError)({statusCode:503,message:"Network error: unable to reach the exchange."})}console_1.logger.error("EXCHANGE",`An error occurred while fetching the exchange balance for userId: ${r.id}`,e);throw(0,error_1.createError)({statusCode:500,message:"Failed to retrieve exchange balance"})}};