"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const db_1=require("@b/db"),query_1=require("@b/utils/query"),error_1=require("@b/utils/error"),wallet_1=require("@b/services/wallet");exports.metadata={summary:"Performs a custom fiat withdraw transaction",description:"Initiates a custom fiat withdraw transaction for the currently authenticated user",operationId:"createCustomFiatWithdraw",tags:["Wallets"],requiresAuth:!0,logModule:"FIAT_WITHDRAW",logTitle:"Process fiat withdrawal",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{methodId:{type:"string",description:"Withdraw method ID"},amount:{type:"number",description:"Amount to withdraw"},currency:{type:"string",description:"Currency to withdraw"},customFields:{type:"object",description:"Custom data for the withdraw"}},required:["methodId","amount","currency","customFields"]}}}},responses:{200:{description:"Custom withdraw transaction initiated successfully",content:{"application/json":{schema:{type:"object",properties:{transaction:{type:"object"},currency:{type:"string"},method:{type:"string"},balance:{type:"number"}}}}}},401:query_1.unauthorizedResponse,404:(0,query_1.notFoundMetadataResponse)("Withdraw Method"),500:query_1.serverErrorResponse}};exports.default=async e=>{const{user:t,body:r,ctx:a}=e;if(!(null==t?void 0:t.id)){null==a||a.fail("User not authenticated");throw(0,error_1.createError)({statusCode:401,message:"Unauthorized"})}const{methodId:n,amount:o,currency:i,customFields:s}=r;null==a||a.step("Verifying user account");if(!await db_1.models.user.findByPk(t.id)){null==a||a.fail("User account not found");throw(0,error_1.createError)({statusCode:404,message:"User not found"})}null==a||a.step("Validating withdrawal method");const d=await db_1.models.withdrawMethod.findByPk(n);if(!d){null==a||a.fail(`Withdrawal method not found: ${n}`);throw(0,error_1.createError)({statusCode:404,message:"Withdraw method not found"})}null==a||a.step("Validating currency");if(!await db_1.models.currency.findOne({where:{id:i}})){null==a||a.fail(`Currency not found: ${i}`);throw(0,error_1.createError)({statusCode:404,message:"Currency not found"})}null==a||a.step("Calculating withdrawal fees");const c=Math.abs(parseFloat(o)),l=d.fixedFee||0,u=d.percentageFee||0,w=parseFloat(Math.max(c*u/100+l,0).toFixed(2)),p=parseFloat((c-w).toFixed(2));null==a||a.step("Processing withdrawal transaction");const f=await db_1.sequelize.transaction(async e=>{null==a||a.step("Locking user wallet for update");const r=await db_1.models.wallet.findOne({where:{userId:t.id,currency:i,type:"FIAT"},transaction:e,lock:e.LOCK.UPDATE});if(!r){null==a||a.fail(`${i} FIAT wallet not found`);throw(0,error_1.createError)({statusCode:404,message:"Wallet not found"})}null==a||a.step("Checking wallet balance");if(r.balance<c){null==a||a.fail(`Insufficient balance: ${r.balance} < ${c}`);throw(0,error_1.createError)({statusCode:400,message:"Insufficient funds"})}null==a||a.step("Deducting funds from wallet via wallet service");const n=`fiat_withdraw_${t.id}_${i}_${c}`,o=await wallet_1.walletService.debit({idempotencyKey:n,userId:t.id,walletId:r.id,walletType:"FIAT",currency:i,amount:c,operationType:"WITHDRAW",description:`Withdrawal of ${p} ${i} (fee: ${w}) via ${d.title}`,metadata:{method:d.title,totalAmount:c,netAmount:p,fee:w,...s},transaction:e});r.balance-=c;null==a||a.step("Recording admin profit from fees");await db_1.models.adminProfit.create({amount:w,currency:r.currency,type:"WITHDRAW",transactionId:o.transactionId,description:`User (${t.id}) withdrawal fee of ${w} ${r.currency} by ${d.title}`},{transaction:e});return{transaction:await db_1.models.transaction.findByPk(o.transactionId,{transaction:e}),currency:r.currency,method:d.title,balance:r.balance}});null==a||a.success(`Withdrawn ${c} ${i} (net: ${p}) via ${d.title}`);return f};