"use strict";function parseMetadata(e){let t={};try{e=e.replace(/\\/g,"");t=JSON.parse(e)||{}}catch(e){console_1.logger.error("WITHDRAW","Invalid JSON in metadata",e)}return t}async function handleWalletRejection(e,t,a){const r=Number(e.amount);if(r>0){const s=`withdraw_reject_${e.id}`;await wallet_1.walletService.credit({idempotencyKey:s,userId:e.userId,walletId:t.id,walletType:t.type,currency:t.currency,amount:r,operationType:"REFUND_WITHDRAWAL",referenceId:e.id,description:`Withdrawal rejected - refund ${r} ${t.currency}`,metadata:{transactionId:e.id,reason:"rejected"},transaction:a})}}async function handleWalletCompletion(){}Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const query_1=require("@b/utils/query"),db_1=require("@b/db"),utils_1=require("@b/api/finance/transaction/utils"),emails_1=require("@b/utils/emails"),console_1=require("@b/utils/console"),wallet_1=require("@b/services/wallet"),error_1=require("@b/utils/error");exports.metadata={summary:"Updates an existing transaction",operationId:"updateTransaction",tags:["Admin","Wallets","Transactions"],parameters:[{index:0,name:"id",in:"path",description:"The ID of the transaction to update",required:!0,schema:{type:"string"}}],requestBody:{required:!0,description:"Updated data for the transaction",content:{"application/json":{schema:utils_1.transactionUpdateSchema}}},responses:(0,query_1.updateRecordResponses)("Transaction"),requiresAuth:!0,permission:"edit.withdraw",logModule:"ADMIN_FIN",logTitle:"Update Withdraw Log"};exports.default=async e=>{const{body:t,params:a,ctx:r}=e,{id:s}=a,{status:n,amount:i,fee:o,description:d,referenceId:c,metadata:l}=t;null==r||r.step("Fetching transaction");const u=await db_1.models.transaction.findOne({where:{id:s}});if(!u)throw(0,error_1.createError)({statusCode:404,message:"Transaction not found"});if("PENDING"!==u.status)throw(0,error_1.createError)({statusCode:400,message:"Only pending transactions can be updated"});u.amount=i;u.fee=o;u.description=d;u.referenceId=c;null==r||r.step("Updating transaction and processing wallet changes");const p=await db_1.sequelize.transaction(async e=>{const t=parseMetadata(u.metadata),a=await db_1.models.wallet.findOne({where:{id:u.walletId},transaction:e});if(!a)throw(0,error_1.createError)({statusCode:404,message:"Wallet not found"});if("PENDING"===u.status){"REJECTED"===n?await handleWalletRejection(u,a,e):"COMPLETED"===n&&await handleWalletCompletion(a,e);null==r||r.step("Sending status update email");const s=await db_1.models.user.findOne({where:{id:u.userId}});s&&await(0,emails_1.sendTransactionStatusUpdateEmail)(s,u,a,a.balance,t.message||null)}l&&(t.message=l.message);u.metadata=JSON.stringify(t);u.status=n;await u.save({transaction:e});return{message:"Transaction updated successfully"}});null==r||r.success("Withdraw log updated successfully");return p};