"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const db_1=require("@b/db"),wallet_1=require("@b/services/wallet"),error_1=require("@b/utils/error"),emails_1=require("@b/utils/emails"),console_1=require("@b/utils/console"),utils_1=require("./utils");exports.metadata={summary:"Verifies PayFast payment return",description:"Handles PayFast return URL verification after payment completion",operationId:"verifyPayFastPayment",tags:["Finance","Deposit","PayFast"],requiresAuth:!0,logModule:"PAYFAST_DEPOSIT",logTitle:"Verify PayFast payment",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{m_payment_id:{type:"string",description:"Merchant payment ID"},pf_payment_id:{type:"string",description:"PayFast payment ID"},payment_status:{type:"string",description:"Payment status from PayFast"},amount_gross:{type:"string",description:"Gross payment amount"},signature:{type:"string",description:"PayFast signature for verification"}},required:["m_payment_id","payment_status"]}}}},responses:{200:{description:"Payment verification completed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},data:{type:"object",properties:{transactionId:{type:"string"},status:{type:"string"},amount:{type:"number"},currency:{type:"string"},paymentId:{type:"string"},verified:{type:"boolean"}}}}}}}},400:{description:"Bad request - invalid parameters"},401:{description:"Unauthorized"},404:{description:"Transaction not found"},500:{description:"Internal server error"}}};exports.default=async t=>{var e,a,r;const{body:s,user:i}=t;if(!(null==i?void 0:i.id))throw(0,error_1.createError)({statusCode:401,message:"Authentication required"});if(!s.m_payment_id||!s.payment_status)throw(0,error_1.createError)({statusCode:400,message:"Payment ID and status are required"});(0,utils_1.validatePayFastConfig)();try{const t=await db_1.models.transaction.findOne({where:{uuid:s.m_payment_id,userId:i.id,status:"PENDING"},include:[{model:db_1.models.user,as:"user",attributes:["id","email","firstName","lastName"]}]});if(!t)throw(0,error_1.createError)({statusCode:404,message:"Transaction not found or already processed"});if(s.signature&&utils_1.PAYFAST_CONFIG.PASSPHRASE){if(!(0,utils_1.validateSignature)(s,utils_1.PAYFAST_CONFIG.PASSPHRASE))throw(0,error_1.createError)({statusCode:400,message:"Invalid payment signature"})}const n=(0,utils_1.mapPayFastStatus)(s.payment_status),o=s.amount_gross?(0,utils_1.parsePayFastAmount)(s.amount_gross):t.amount,d=s.amount_fee?(0,utils_1.parsePayFastAmount)(s.amount_fee):0,u=s.amount_net?(0,utils_1.parsePayFastAmount)(s.amount_net):o-d,m=await db_1.sequelize.transaction();try{await t.update({status:n,fee:d,metadata:{...t.metadata,payfast:{...null===(e=t.metadata)||void 0===e?void 0:e.payfast,pf_payment_id:s.pf_payment_id,payment_status:s.payment_status,amount_gross:o,amount_fee:d,amount_net:u,verified_at:(new Date).toISOString(),signature_valid:!!s.signature,return_data:s}}},{transaction:m});if("COMPLETED"===n){const e=(null===(a=t.metadata)||void 0===a?void 0:a.currency)||"ZAR",r=(await wallet_1.walletCreationService.getOrCreateWallet(i.id,"FIAT",e,m)).wallet,n=`payfast_verify_${t.id}`;await wallet_1.walletService.credit({idempotencyKey:n,userId:i.id,walletId:r.id,walletType:"FIAT",currency:e,amount:u,operationType:"DEPOSIT",referenceId:t.id,description:`PayFast deposit of ${u} ${e}`,metadata:{method:"PAYFAST",paymentId:s.pf_payment_id,fee:d},transaction:m});const o=parseFloat(String(r.balance))+u;try{await(0,emails_1.sendFiatTransactionEmail)(t.user,t,e,o)}catch(t){console_1.logger.error("PAYFAST","Failed to send confirmation email",t)}}await m.commit();return{success:!0,data:{transactionId:t.id,status:n,amount:o,currency:(null===(r=t.metadata)||void 0===r?void 0:r.currency)||"ZAR",paymentId:s.pf_payment_id||s.m_payment_id,verified:!0,fee:d,netAmount:u}}}catch(t){await m.rollback();throw t}}catch(t){console_1.logger.error("PAYFAST","Verification error",t);throw(0,error_1.createError)({statusCode:t.statusCode||500,message:t.message||"Failed to verify PayFast payment"})}};