"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const emails_1=require("@b/utils/emails"),db_1=require("@b/db"),error_1=require("@b/utils/error"),query_1=require("@b/utils/query"),utils_1=require("../../wallet/utils"),console_1=require("@b/utils/console"),wallet_1=require("@b/services/wallet");exports.metadata={summary:"Cancels an investment",description:"Allows a user to cancel an existing investment by its UUID. The operation reverses any financial transactions associated with the investment and updates the user's wallet balance accordingly.",operationId:"cancelInvestment",tags:["Finance","Investment"],logModule:"FINANCE",logTitle:"Cancel investment",requiresAuth:!0,parameters:[{index:0,name:"id",in:"path",description:"The ID of the investment to cancel",required:!0,schema:{type:"string"}},{name:"type",in:"query",description:"The type of investment to retrieve",schema:{type:"string"}}],responses:{200:{description:"Investment canceled successfully",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}},401:query_1.unauthorizedResponse,404:(0,query_1.notFoundMetadataResponse)("Investment"),500:query_1.serverErrorResponse}};exports.default=async e=>{const{user:t,params:n,query:s,ctx:a}=e;if(!t)throw(0,error_1.createError)({statusCode:401,message:"Unauthorized"});const{id:r}=n,{type:i}=s;null==a||a.step("Validating investment type");if(!i||"string"!=typeof i)throw(0,error_1.createError)({statusCode:400,message:"Invalid investment type"});let o,l,d,c;switch(i.toLowerCase()){case"general":l=db_1.models.investment;d=db_1.models.investmentPlan;c=db_1.models.investmentDuration;break;case"forex":l=db_1.models.forexInvestment;d=db_1.models.forexPlan;c=db_1.models.forexDuration}const u=await db_1.models.user.findByPk(t.id);if(!u)throw(0,error_1.createError)({statusCode:404,message:"User not found"});null==a||a.step("Processing investment cancellation");await db_1.sequelize.transaction(async e=>{null==a||a.step("Finding investment");o=await l.findOne({where:{id:r},include:[{model:d,as:"plan"},{model:db_1.models.user,as:"user",attributes:["id","firstName","lastName","email","avatar"]},{model:c,as:"duration"}]});if(!o)throw(0,error_1.createError)({statusCode:404,message:"Investment not found"});null==a||a.step("Finding wallet");const n=await(0,utils_1.getWallet)(t.id,o.plan.walletType,o.plan.currency);if(!n)throw(0,error_1.createError)({statusCode:404,message:"Wallet not found"});const s=await db_1.models.transaction.findOne({where:{referenceId:r}});null==a||a.step("Refunding investment amount via wallet service");const i=`investment_cancel_${r}`;await wallet_1.walletService.credit({idempotencyKey:i,userId:t.id,walletId:n.id,walletType:o.plan.walletType,currency:o.plan.currency,amount:o.amount,operationType:"REFUND",referenceId:r,description:`Investment cancelled - refund ${o.amount} ${o.plan.currency}`,metadata:{investmentId:r,planId:o.plan.id,planName:o.plan.name},transaction:e});null==a||a.step("Deleting investment");await o.destroy({force:!0,transaction:e});s&&await s.destroy({force:!0,transaction:e})});null==a||a.step("Sending cancellation email");try{await(0,emails_1.sendInvestmentEmail)(u,o.plan,o.duration,o,"InvestmentCanceled",a)}catch(e){console_1.logger.error("INVESTMENT","Error sending investment email",e)}null==a||a.success(`Investment ${r} cancelled successfully for user ${t.id}`)};