"use strict";function getOrderByMetric(e){switch(e){case"winRate":return[[(0,sequelize_1.literal)("CASE WHEN COUNT(id) > 0 THEN SUM(CASE WHEN status = 'WIN' THEN 1 ELSE 0 END) * 100.0 / COUNT(id) ELSE 0 END"),"DESC"]];case"volume":return[[(0,sequelize_1.fn)("COUNT",(0,sequelize_1.col)("id")),"DESC"]];default:return[[(0,sequelize_1.literal)("SUM(CASE WHEN status = 'WIN' THEN profit WHEN status = 'LOSS' THEN -amount ELSE 0 END)"),"DESC"]]}}function generateAnonymousName(e,t,r){return`${e.charAt(0).toUpperCase()}${t?t.charAt(0).toUpperCase():""}***${r.slice(-4).toUpperCase()}`}Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const db_1=require("@b/db"),sequelize_1=require("sequelize"),query_1=require("@b/utils/query"),error_1=require("@b/utils/error");exports.metadata={summary:"Get Binary Trading Leaderboard",operationId:"getBinaryLeaderboard",tags:["Exchange","Binary","Leaderboard"],description:"Retrieves the top traders leaderboard for binary options trading. Supports different time periods and ranking metrics.",parameters:[{name:"period",in:"query",description:"Time period for the leaderboard: daily, weekly, monthly, alltime",schema:{type:"string",enum:["daily","weekly","monthly","alltime"]}},{name:"metric",in:"query",description:"Ranking metric: profit (total profit), winRate (win percentage), volume (trade count)",schema:{type:"string",enum:["profit","winRate","volume"]}},{name:"limit",in:"query",description:"Maximum number of traders to return (default 100, max 100)",schema:{type:"number"}}],responses:{200:{description:"Leaderboard data with top traders",content:{"application/json":{schema:{type:"object",properties:{period:{type:"string"},metric:{type:"string"},updatedAt:{type:"string"},traders:{type:"array",items:{type:"object",properties:{rank:{type:"number"},username:{type:"string"},avatar:{type:"string"},totalProfit:{type:"number"},winRate:{type:"number"},totalTrades:{type:"number"},wins:{type:"number"},losses:{type:"number"}}}}}}}}},404:(0,query_1.notFoundMetadataResponse)("Leaderboard"),500:query_1.serverErrorResponse},requiresAuth:!1};exports.default=async e=>{const{query:t,ctx:r}=e,{period:a="weekly",metric:s="profit",limit:i=100}=t;null==r||r.step(`Fetching ${a} leaderboard by ${s}`);const n=new Date;let o;switch(a){case"daily":o=new Date(n.getFullYear(),n.getMonth(),n.getDate());break;case"weekly":const e=n.getDay();o=new Date(n);o.setDate(n.getDate()-e);o.setHours(0,0,0,0);break;case"monthly":o=new Date(n.getFullYear(),n.getMonth(),1);break;default:o=new Date(0)}const l={status:{[sequelize_1.Op.in]:["WIN","LOSS"]},isDemo:!1};"alltime"!==a&&(l.closedAt={[sequelize_1.Op.gte]:o});try{const e=await db_1.models.binaryOrder.findAll({attributes:["userId",[(0,sequelize_1.fn)("COUNT",(0,sequelize_1.col)("id")),"totalTrades"],[(0,sequelize_1.fn)("SUM",(0,sequelize_1.literal)("CASE WHEN status = 'WIN' THEN 1 ELSE 0 END")),"wins"],[(0,sequelize_1.fn)("SUM",(0,sequelize_1.literal)("CASE WHEN status = 'LOSS' THEN 1 ELSE 0 END")),"losses"],[(0,sequelize_1.fn)("SUM",(0,sequelize_1.literal)("CASE WHEN status = 'WIN' THEN profit WHEN status = 'LOSS' THEN -amount ELSE 0 END")),"totalProfit"]],where:l,group:["userId"],having:(0,sequelize_1.literal)("COUNT(id) >= 5"),order:getOrderByMetric(s),limit:Math.min(Number(i),100),raw:!0}),t=e.map(e=>e.userId);if(0===t.length){null==r||r.success("No traders found for this period");return{period:a,metric:s,updatedAt:(new Date).toISOString(),traders:[]}}const n=await db_1.models.user.findAll({attributes:["id","firstName","lastName","avatar"],where:{id:{[sequelize_1.Op.in]:t}},raw:!0}),o=new Map;n.forEach(e=>{o.set(e.id,e)});const u=e.map((e,t)=>{const r=o.get(e.userId),a=Number(e.wins)||0,s=Number(e.losses)||0,i=Number(e.totalTrades)||0,n=i>0?a/i*100:0;return{rank:t+1,username:generateAnonymousName((null==r?void 0:r.firstName)||"Trader",(null==r?void 0:r.lastName)||"",e.userId),avatar:(null==r?void 0:r.avatar)||null,totalProfit:parseFloat(Number(e.totalProfit||0).toFixed(2)),winRate:parseFloat(n.toFixed(1)),totalTrades:i,wins:a,losses:s}});null==r||r.success(`Retrieved ${u.length} traders for leaderboard`);return{period:a,metric:s,updatedAt:(new Date).toISOString(),traders:u}}catch(e){null==r||r.fail(e.message);throw(0,error_1.createError)({statusCode:500,message:`Failed to fetch leaderboard: ${e.message}`})}};