"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const query_1=require("@b/utils/query"),error_1=require("@b/utils/error"),console_1=require("@b/utils/console"),utils_1=require("./utils"),db_1=require("@b/db"),emails_1=require("@b/utils/emails"),utils_2=require("@b/api/finance/utils");exports.metadata={summary:"Verify eWAY payment status",description:"Verify an eWAY payment status using access code and update transaction accordingly",operationId:"verifyEwayPayment",tags:["Finance","Verification"],logModule:"EWAY_DEPOSIT",logTitle:"Verify eWAY payment",requestBody:{description:"Payment verification request",content:{"application/json":{schema:{type:"object",properties:{access_code:{type:"string",description:"eWAY access code from redirect"},transaction_id:{type:"string",description:"Internal transaction ID"},reference:{type:"string",description:"Payment reference ID"}},required:["access_code"]}}}},responses:{200:{description:"Payment verification result",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},data:{type:"object",properties:{transaction_id:{type:"string"},status:{type:"string"},amount:{type:"number"},currency:{type:"string"},gateway_transaction_id:{type:"string"},authorisation_code:{type:"string"},response_code:{type:"string"},response_message:{type:"string"}}}}}}}},400:{description:"Invalid request parameters"},401:query_1.unauthorizedResponse,404:(0,query_1.notFoundMetadataResponse)("Transaction")},requiresAuth:!0};exports.default=async e=>{var t,r,s;const{user:a,body:o,ctx:n}=e;if(!(null==a?void 0:a.id)){null==n||n.fail("User not authenticated");throw(0,error_1.createError)({statusCode:401,message:"User not authenticated"})}try{const{access_code:e,transaction_id:i,reference:c}=o;if(!e)throw(0,error_1.createError)({statusCode:400,message:"Access code is required"});let d;i?d=await db_1.models.transaction.findOne({where:{id:i,userId:a.id,status:"PENDING"},include:[{model:db_1.models.wallet,as:"wallet"}]}):c&&(d=await db_1.models.transaction.findOne({where:{referenceId:c,userId:a.id,status:"PENDING"},include:[{model:db_1.models.wallet,as:"wallet"}]}));if(!d)throw(0,error_1.createError)({statusCode:404,message:"Transaction not found or already processed"});const u=await(0,utils_1.makeEwayRequest)(`/GetAccessCodeResult/${e}`,"GET");if(u.Errors){console_1.logger.error("EWAY","Verification error",u.Errors);await d.update({status:"FAILED",metadata:JSON.stringify({...d.metadata,eway_errors:u.Errors,eway_response_code:u.ResponseCode,eway_response_message:u.ResponseMessage,verified_at:(new Date).toISOString()})});return{success:!1,data:{transaction_id:d.id,status:"FAILED",amount:d.amount,currency:d.metadata.currency,response_code:u.ResponseCode,response_message:u.ResponseMessage,errors:u.Errors}}}const l=!0===u.TransactionStatus,p=l?"COMPLETED":"FAILED";if(l){d.wallet;const s=(null===(t=d.metadata)||void 0===t?void 0:t.currency)||"AUD",o=d.fee||0;null==n||n.step("Processing deposit via wallet service");const i=await(0,utils_2.processFiatDeposit)({userId:a.id,currency:s,amount:d.amount,fee:o,referenceId:(null===(r=u.TransactionID)||void 0===r?void 0:r.toString())||e,method:"EWAY",description:`eWAY deposit - ${d.amount} ${s}`,metadata:{eway_transaction_id:u.TransactionID,eway_authorisation_code:u.AuthorisationCode},idempotencyKey:`eway_deposit_${u.TransactionID||e}`,ctx:n});try{null==n||n.step("Sending notification email");await(0,emails_1.sendFiatTransactionEmail)(a,d,s,i.newBalance)}catch(e){console_1.logger.error("EWAY","Failed to send deposit confirmation email",e)}}await d.update({status:p,metadata:JSON.stringify({...d.metadata,eway_transaction_id:u.TransactionID,eway_authorisation_code:u.AuthorisationCode,eway_response_code:u.ResponseCode,eway_response_message:u.ResponseMessage,eway_transaction_type:u.TransactionType,eway_beagle_score:u.BeagleScore,verified_at:(new Date).toISOString()})});return{success:!0,data:{transaction_id:d.id,status:p,amount:d.amount,currency:d.metadata.currency,gateway_transaction_id:null===(s=u.TransactionID)||void 0===s?void 0:s.toString(),authorisation_code:u.AuthorisationCode,response_code:u.ResponseCode,response_message:u.ResponseMessage,beagle_score:u.BeagleScore}}}catch(e){console_1.logger.error("EWAY","Verification error",e);if(e instanceof utils_1.EwayError)throw(0,error_1.createError)({statusCode:400,message:`eWAY Error: ${e.message}`});throw(0,error_1.createError)({statusCode:500,message:e.message||"Failed to verify eWAY payment"})}};