"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:"Checks Paysafe payment status",description:"Queries current payment status from Paysafe and updates local transaction record",operationId:"checkPaysafePaymentStatus",tags:["Finance","Deposit","Paysafe"],requiresAuth:!0,parameters:[{name:"reference",in:"query",required:!0,schema:{type:"string",description:"Transaction reference number"}},{name:"payment_id",in:"query",required:!1,schema:{type:"string",description:"Paysafe payment ID (optional)"}}],responses:{200:{description:"Payment status retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},data:{type:"object",properties:{transaction_id:{type:"string"},reference:{type:"string"},status:{type:"string"},gateway_status:{type:"string"},amount:{type:"number"},currency:{type:"string"},payment_id:{type:"string"},gateway_transaction_id:{type:"string"},created_at:{type:"string"},updated_at:{type:"string"},expires_at:{type:"string"},is_expired:{type:"boolean"},checkout_url:{type:"string"},return_url:{type:"string"},processor:{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,s,r,n,o,i,d,u,l,c,p,y,m,_,v,g;const{user:f,query:h}=e,{reference:w,payment_id:I}=h;if(!(null==f?void 0:f.id))throw(0,error_1.createError)({statusCode:401,message:"User not authenticated"});if(!w)throw(0,error_1.createError)({statusCode:400,message:"Transaction reference is required"});try{(0,utils_1.validatePaysafeConfig)();const e=await db_1.models.transaction.findOne({where:{uuid:w,userId:f.id}});if(!e)throw(0,error_1.createError)({statusCode:404,message:"Transaction not found"});const h=new Date(e.createdAt),S=new Date(h.getTime()+36e5),E=new Date>S;E&&"PENDING"===e.status&&await e.update({status:"EXPIRED",metadata:{...e.metadata,expiredAt:(new Date).toISOString()}});let P=null,k=(null===(t=e.metadata)||void 0===t?void 0:t.gatewayStatus)||"UNKNOWN",b=(null===(a=e.metadata)||void 0===a?void 0:a.gatewayTransactionId)||null,A=(null===(s=e.metadata)||void 0===s?void 0:s.processorId)||"PAYSAFE";if(!E&&"PENDING"===e.status)try{if(I)P=await(0,utils_1.makeApiRequest)(`payments/${I}`,{method:"GET"});else{const e=await(0,utils_1.makeApiRequest)(`payments?merchantRefNum=${w}`,{method:"GET"});Array.isArray(e)&&e.length>0&&(P=e[0])}if(P){const t=(0,utils_1.mapPaysafeStatus)(P.status);k=P.status;b=P.gatewayReconciliationId||P.id;A=(null===(r=P.gatewayResponse)||void 0===r?void 0:r.processor)||"PAYSAFE";if(e.status!==t){await e.update({status:t,metadata:{...e.metadata,paymentId:P.id,gatewayTransactionId:b,gatewayStatus:k,processorId:A,lastStatusCheck:(new Date).toISOString(),gatewayResponse:P.gatewayResponse}});e.status=t}}}catch(e){console_1.logger.error("PAYSAFE","Failed to get payment status from Paysafe",e)}const q=process.env.NEXT_PUBLIC_SITE_URL||"http://localhost:3000",T=(null===(n=e.metadata)||void 0===n?void 0:n.checkoutUrl)||`${q}/user/wallet/deposit`,D=`${q}/user/wallet/deposit/paysafe/verify`;return{success:!0,data:{transaction_id:e.id,reference:e.uuid,status:e.status,gateway_status:k,amount:e.amount,currency:(null===(o=e.metadata)||void 0===o?void 0:o.currency)||"USD",payment_id:(null===(i=e.metadata)||void 0===i?void 0:i.paymentId)||I||null,gateway_transaction_id:b,created_at:null===(d=e.createdAt)||void 0===d?void 0:d.toISOString(),updated_at:null===(u=e.updatedAt)||void 0===u?void 0:u.toISOString(),expires_at:S.toISOString(),is_expired:E,checkout_url:T,return_url:D,processor:A,payment_handle_id:(null===(l=e.metadata)||void 0===l?void 0:l.paymentHandleId)||null,payment_handle_token:(null===(c=e.metadata)||void 0===c?void 0:c.paymentHandleToken)||null,gateway_response:(null===(p=e.metadata)||void 0===p?void 0:p.gatewayResponse)||null,last_status_check:(null===(y=e.metadata)||void 0===y?void 0:y.lastStatusCheck)||null,webhook_events:{last_event_id:(null===(m=e.metadata)||void 0===m?void 0:m.webhookEventId)||null,last_event_type:(null===(_=e.metadata)||void 0===_?void 0:_.webhookEventType)||null,last_event_time:(null===(v=e.metadata)||void 0===v?void 0:v.webhookEventTime)||null,last_webhook_update:(null===(g=e.metadata)||void 0===g?void 0:g.lastWebhookUpdate)||null}}}}catch(e){console_1.logger.error("PAYSAFE","Status check error",e);if(e instanceof utils_1.PaysafeError)throw(0,error_1.createError)({statusCode:e.status,message:`Paysafe Error: ${e.message}`});throw(0,error_1.createError)({statusCode:500,message:e.message||"Failed to check Paysafe payment status"})}};