"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:"Handles Paystack webhook notifications",description:"Processes real-time payment status updates from Paystack webhooks",operationId:"handlePaystackWebhook",tags:["Finance","Deposit","Paystack","Webhook"],logModule:"WEBHOOK",logTitle:"Paystack webhook",requiresAuth:!1,requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{event:{type:"string",description:"Webhook event type",example:"charge.success"},data:{type:"object",description:"Transaction data from Paystack"}},required:["event","data"]}}}},responses:{200:{description:"Webhook processed successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},message:{type:"string"}}}}}},400:{description:"Bad request - Invalid webhook data"},401:{description:"Unauthorized - Invalid signature"},404:{description:"Transaction not found"},500:{description:"Internal server error"}}};exports.default=async e=>{const{body:t,headers:r}=e,a=r["x-paystack-signature"];try{const e=JSON.stringify(t);if(!a||!(0,utils_1.validateWebhookSignature)(e,a))throw(0,error_1.createError)({statusCode:401,message:"Invalid webhook signature"});const r=t,{event:s,data:o}=r;console_1.logger.info("PAYSTACK",`Received webhook: ${s} - ref: ${o.reference}, status: ${o.status}`);if(s!==utils_1.PAYSTACK_WEBHOOK_EVENTS.CHARGE_SUCCESS){console_1.logger.debug("PAYSTACK",`Ignoring webhook event: ${s}`);return{success:!0,message:`Event ${s} acknowledged but not processed`}}const n=await db_1.models.transaction.findOne({where:{id:o.reference},include:[{model:db_1.models.user,as:"user",attributes:["id","email","firstName","lastName"]}]});if(!n){console_1.logger.warn("PAYSTACK",`Transaction not found for reference: ${o.reference}`);throw(0,error_1.createError)({statusCode:404,message:"Transaction not found"})}const c=n.user;if(!c)throw(0,error_1.createError)({statusCode:404,message:"User not found for transaction"});if(["COMPLETED","FAILED","CANCELLED","REFUNDED"].includes(n.status)){console_1.logger.debug("PAYSTACK",`Transaction ${n.id} already in final state: ${n.status}`);return{success:!0,message:"Transaction already processed"}}const i=(0,utils_1.mapPaystackStatus)(o.status),u=(0,utils_1.parsePaystackAmount)(o.amount,o.currency),d=(0,utils_1.parsePaystackAmount)(o.fees||0,o.currency);if(Math.abs(u-n.amount)>.01){console_1.logger.error("PAYSTACK",`Amount mismatch for transaction ${n.id}: expected ${n.amount}, got ${u}`);throw(0,error_1.createError)({statusCode:400,message:"Transaction amount mismatch"})}if(o.currency!==n.currency){console_1.logger.error("PAYSTACK",`Currency mismatch for transaction ${n.id}: expected ${n.currency}, got ${o.currency}`);throw(0,error_1.createError)({statusCode:400,message:"Transaction currency mismatch"})}const l=await db_1.sequelize.transaction();try{await n.update({status:i,referenceId:o.reference,fee:d,metadata:JSON.stringify({...JSON.parse(n.metadata||"{}"),paystack_transaction_id:o.id,paystack_status:o.status,gateway_response:o.gateway_response,paid_at:o.paid_at,channel:o.channel,authorization:o.authorization,customer:o.customer,fees_breakdown:o.fees_breakdown,webhook_processed_at:(new Date).toISOString()})},{transaction:l});if("COMPLETED"===i){const e=(await wallet_1.walletCreationService.getOrCreateWallet(c.id,"FIAT",n.currency,l)).wallet,t=`paystack_webhook_${n.id}`;await wallet_1.walletService.credit({idempotencyKey:t,userId:c.id,walletId:e.id,walletType:"FIAT",currency:n.currency,amount:n.amount,operationType:"DEPOSIT",referenceId:n.id,description:`Paystack deposit of ${n.amount} ${n.currency}`,metadata:{method:"PAYSTACK",paystackTransactionId:o.id},transaction:l});console_1.logger.success("PAYSTACK",`Wallet updated for user ${c.id}: +${n.amount} ${n.currency}`)}await l.commit();console_1.logger.info("PAYSTACK",`Transaction ${n.id} updated to status: ${i}`);if("COMPLETED"===i)try{const e=await db_1.models.wallet.findOne({where:{userId:c.id,currency:n.currency}}),t=(null==e?void 0:e.balance)||n.amount;await(0,emails_1.sendFiatTransactionEmail)(c,n,n.currency,t);console_1.logger.success("PAYSTACK",`Confirmation email sent for transaction ${n.id}`)}catch(e){console_1.logger.error("PAYSTACK","Failed to send confirmation email",e)}return{success:!0,message:"Webhook processed successfully"}}catch(e){await l.rollback();console_1.logger.error("PAYSTACK","Database error processing webhook",e);throw e}}catch(e){console_1.logger.error("PAYSTACK","Error processing webhook",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 process webhook"})}};