"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const db_1=require("@b/db"),error_1=require("@b/utils/error"),console_1=require("@b/utils/console"),utils_1=require("./utils");exports.metadata={summary:"Check PayFast payment status",description:"Queries current payment status from PayFast and updates local records",operationId:"checkPayFastStatus",tags:["Finance","Deposit","PayFast"],requiresAuth:!0,parameters:[{name:"transactionId",in:"query",required:!0,schema:{type:"string",description:"Transaction ID to check"}}],responses:{200:{description:"Payment status retrieved successfully",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"},reference:{type:"string"},updated:{type:"boolean"},paymentUrl:{type:"string"}}}}}}}},400:{description:"Bad request - invalid parameters"},401:{description:"Unauthorized"},404:{description:"Transaction not found"},500:{description:"Internal server error"}}};exports.default=async e=>{var t,a,r;const{query:s,user:n}=e;if(!(null==n?void 0:n.id))throw(0,error_1.createError)({statusCode:401,message:"Authentication required"});if(!s.transactionId)throw(0,error_1.createError)({statusCode:400,message:"Transaction ID is required"});(0,utils_1.validatePayFastConfig)();try{const e=await db_1.models.transaction.findOne({where:{id:s.transactionId,userId:n.id}});if(!e)throw(0,error_1.createError)({statusCode:404,message:"Transaction not found"});const o=null===(t=e.metadata)||void 0===t?void 0:t.payfast;if(!o||!o.pf_payment_id)return{success:!0,data:{transactionId:e.id,status:e.status,amount:e.amount,currency:(null===(a=e.metadata)||void 0===a?void 0:a.currency)||"ZAR",paymentId:(null==o?void 0:o.m_payment_id)||e.uuid,reference:e.uuid,updated:!1,paymentUrl:null}};let i=!1,d=e.status,c=null;const u=new Date(e.createdAt);try{"PENDING"===d&&(c=`https://${(0,utils_1.getPayFastHost)()}/eng/process`);const t=((new Date).getTime()-u.getTime())/36e5;if("PENDING"===d&&t>1){await e.update({status:"EXPIRED",metadata:{...e.metadata,payfast:{...o,expired_at:(new Date).toISOString(),expiry_reason:"Payment session timeout"}}});d="EXPIRED";i=!0;c=null}}catch(e){console_1.logger.error("PAYFAST","Status check error",e)}return{success:!0,data:{transactionId:e.id,status:d,amount:e.amount,currency:(null===(r=e.metadata)||void 0===r?void 0:r.currency)||"ZAR",paymentId:o.pf_payment_id||o.m_payment_id,reference:e.uuid,updated:i,paymentUrl:c,metadata:{gateway:"payfast",createdAt:e.createdAt,lastUpdated:e.updatedAt,merchantId:o.merchant_id,paymentForm:o.payment_form,expiresAt:new Date(u.getTime()+36e5).toISOString()}}}}catch(e){console_1.logger.error("PAYFAST","Status check error",e);throw(0,error_1.createError)({statusCode:e.statusCode||500,message:e.message||"Failed to check PayFast payment status"})}};