"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"),console_1=require("@b/utils/console"),utils_1=require("./utils");exports.metadata={summary:"Checks Paystack payment status",description:"Queries current payment status from Paystack and updates local transaction records",operationId:"checkPaystackPaymentStatus",tags:["Finance","Deposit","Paystack"],requiresAuth:!0,parameters:[{name:"reference",in:"query",required:!0,schema:{type:"string",description:"Payment reference to check"}}],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"},amount:{type:"number"},currency:{type:"string"},gateway:{type:"string"},gateway_response:{type:"string"},paid_at:{type:"string"},channel:{type:"string"},fees:{type:"number"},authorization_url:{type:"string"},expired:{type:"boolean"},expires_at:{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=>{const{user:t,query:a}=e,{reference:r}=a;if(!(null==t?void 0:t.id))throw(0,error_1.createError)({statusCode:401,message:"User not authenticated"});if(!r)throw(0,error_1.createError)({statusCode:400,message:"Payment reference is required"});try{(0,utils_1.validatePaystackConfig)();const e=await db_1.models.transaction.findOne({where:{id:r,userId:t.id}});if(!e)throw(0,error_1.createError)({statusCode:404,message:"Transaction not found"});const a=JSON.parse(e.metadata||"{}"),s=a.authorization_url||"",n=new Date(e.createdAt),i=new Date,c=n<new Date(i.getTime()-36e5)&&"PENDING"===e.status;if(["COMPLETED","FAILED","CANCELLED","REFUNDED"].includes(e.status)||c)return{success:!0,data:{transaction_id:e.id,reference:r,status:c?"EXPIRED":e.status,amount:e.amount,currency:e.currency,gateway:"paystack",gateway_response:a.gateway_response||"N/A",paid_at:a.paid_at||null,channel:a.channel||"unknown",fees:e.fee||0,authorization_url:s,expired:c,expires_at:new Date(n.getTime()+36e5).toISOString()}};try{const i=await(0,utils_1.makePaystackRequest)(`/transaction/verify/${r}`,{method:"GET"});if(i.status&&i.data){const c=i.data,o=(0,utils_1.mapPaystackStatus)(c.status),u=(0,utils_1.parsePaystackAmount)(c.amount,c.currency),d=(0,utils_1.parsePaystackAmount)(c.fees||0,c.currency);if(o!==e.status){await e.update({status:o,referenceId:c.reference,fee:d,metadata:JSON.stringify({...a,paystack_transaction_id:c.id,paystack_status:c.status,gateway_response:c.gateway_response,paid_at:c.paid_at,channel:c.channel,authorization:c.authorization,customer:c.customer,fees_breakdown:c.fees_breakdown,status_checked_at:(new Date).toISOString()})});if("COMPLETED"===o&&"COMPLETED"!==e.status){const a=(await wallet_1.walletCreationService.getOrCreateWallet(t.id,"FIAT",e.currency)).wallet,r=`paystack_status_${e.id}`;await wallet_1.walletService.credit({idempotencyKey:r,userId:t.id,walletId:a.id,walletType:"FIAT",currency:e.currency,amount:e.amount,operationType:"DEPOSIT",referenceId:e.id,description:`Paystack deposit of ${e.amount} ${e.currency}`,metadata:{method:"PAYSTACK",paystackTransactionId:c.id}})}}return{success:!0,data:{transaction_id:e.id,reference:r,status:o,amount:u,currency:c.currency,gateway:"paystack",gateway_response:c.gateway_response,paid_at:c.paid_at,channel:c.channel,fees:d,authorization_url:s,expired:!1,expires_at:new Date(n.getTime()+36e5).toISOString()}}}}catch(e){console_1.logger.warn("PAYSTACK","Failed to check Paystack status",e)}return{success:!0,data:{transaction_id:e.id,reference:r,status:e.status,amount:e.amount,currency:e.currency,gateway:"paystack",gateway_response:a.gateway_response||"Status check failed",paid_at:a.paid_at||null,channel:a.channel||"unknown",fees:e.fee||0,authorization_url:s,expired:c,expires_at:new Date(n.getTime()+36e5).toISOString()}}}catch(e){if(e instanceof utils_1.PaystackError)throw(0,error_1.createError)({statusCode:e.status,message:e.message});if(e.statusCode)throw e;throw(0,error_1.createError)({statusCode:500,message:"Failed to check payment status"})}};