"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")),db_1=require("@b/db"),console_1=require("@b/utils/console");exports.metadata={summary:"Calculates and compares the fees for exchange orders, grouped by fee currency",description:"Fetches the orders, calculates the fees, and groups them by fee currency.",operationId:"getOrderFeesByCurrency",tags:["Admin","Exchange","Fees"],requiresAuth:!0,responses:{200:{description:"Fees calculated and compared successfully, grouped by fee currency",content:{"application/json":{schema:{type:"object",properties:{feesComparison:{type:"array",items:{type:"object",properties:{currency:{type:"string",description:"The fee currency"},totalAmount:{type:"number",description:"The total order amount"},totalCalculatedFee:{type:"number",description:"The total calculated fee"},totalExchangeFee:{type:"number",description:"The total fee from the exchange"},totalExtraFee:{type:"number",description:"The total extra fee we charged"}}}}}}}}},401:query_1.unauthorizedResponse,500:query_1.serverErrorResponse},permission:"view.exchange.fee"};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 o=await e.fetchMarkets(),a=await db_1.models.exchangeOrder.findAll({where:{userId:r.id},attributes:["id","amount","fee","symbol","side","feeCurrency"]}),s={};a.forEach(e=>{const r=o.find(r=>r.symbol===e.symbol),t="BUY"===e.side?r.taker:r.maker,a=e.amount*e.fee/100,c=e.amount*t/100,n=a-c;s[e.feeCurrency]||(s[e.feeCurrency]={currency:e.feeCurrency,totalAmount:0,totalCalculatedFee:0,totalExchangeFee:0,totalExtraFee:0});s[e.feeCurrency].totalAmount+=e.amount;s[e.feeCurrency].totalCalculatedFee+=a;s[e.feeCurrency].totalExchangeFee+=c;s[e.feeCurrency].totalExtraFee+=n});return{feesComparison:Object.values(s)}}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 fees for userId: ${r.id}`,e);throw(0,error_1.createError)({statusCode:500,message:"Failed to retrieve exchange fees"})}};