"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const db_1=require("@b/db"),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 Paytm webhook notifications",description:"Processes real-time payment notifications from Paytm with checksum verification and status updates",operationId:"paytmWebhook",tags:["Finance","Deposit","Paytm","Webhook"],logModule:"WEBHOOK",logTitle:"Paytm webhook",requiresAuth:!1,requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{orderId:{type:"string"},mid:{type:"string"},txnId:{type:"string"},txnAmount:{type:"string"},paymentMode:{type:"string"},currency:{type:"string"},txnDate:{type:"string"},status:{type:"string"},respCode:{type:"string"},respMsg:{type:"string"},gatewayName:{type:"string"},bankTxnId:{type:"string"},bankName:{type:"string"},checksumhash:{type:"string"}},required:["orderId","mid","status","checksumhash"]}}}},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 checksum"},404:{description:"Transaction not found"},500:{description:"Internal server error"}}};exports.default=async e=>{const{body:t,headers:s}=e,r=t;try{(0,utils_1.validatePaytmConfig)();if(!(r.orderId&&r.mid&&r.status&&r.checksumhash))throw(0,error_1.createError)({statusCode:400,message:"Missing required webhook fields"});if(r.mid!==utils_1.PAYTM_CONFIG.MID)throw(0,error_1.createError)({statusCode:400,message:"Invalid merchant ID"});const{checksumhash:e,...t}=r;if(!(0,utils_1.verifyChecksumHash)(t,e,utils_1.PAYTM_CONFIG.MERCHANT_KEY))throw(0,error_1.createError)({statusCode:401,message:"Invalid webhook signature"});const s=await db_1.models.transaction.findOne({where:{uuid:r.orderId,type:"DEPOSIT"},include:[{model:db_1.models.user,as:"user"}]});if(!s)throw(0,error_1.createError)({statusCode:404,message:"Transaction not found"});const a=s.user;if(!a)throw(0,error_1.createError)({statusCode:404,message:"User not found for transaction"});const o=JSON.parse(s.metadata||"{}");if("paytm"!==o.gateway)throw(0,error_1.createError)({statusCode:400,message:"Invalid gateway for this transaction"});const n=(0,utils_1.mapPaytmStatus)(r.status),i=(0,utils_1.parsePaytmAmount)(r.txnAmount||"0",r.currency||"INR");if(s.status===n)return{success:!0,message:"Webhook processed - no status change"};const c=await db_1.sequelize.transaction();try{await s.update({status:n,referenceId:r.txnId||s.referenceId,metadata:JSON.stringify({...o,txnId:r.txnId,bankTxnId:r.bankTxnId,paymentMode:r.paymentMode,bankName:r.bankName,gatewayName:r.gatewayName,respCode:r.respCode,respMsg:r.respMsg,txnDate:r.txnDate,webhookProcessedAt:(new Date).toISOString(),webhookData:r})},{transaction:c});if("COMPLETED"===n){const e=await db_1.models.wallet.findOne({where:{userId:a.id,currency:r.currency||"INR",type:"FIAT"},transaction:c});if(!e){await c.rollback();throw(0,error_1.createError)({statusCode:400,message:"User wallet not found"})}{const t=parseFloat(e.balance)+i;await e.update({balance:t.toString()},{transaction:c});await c.commit();try{await(0,emails_1.sendFiatTransactionEmail)(a,s,r.currency||"INR",t)}catch(e){console_1.logger.error("PAYTM","Failed to send confirmation email",e)}}}else await c.commit();console_1.logger.success("PAYTM",`Webhook processed: Order ${r.orderId}, Status: ${n}, Amount: ${i}`);return{success:!0,message:"Webhook processed successfully"}}catch(e){await c.rollback();throw e}}catch(e){if(e instanceof utils_1.PaytmError)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 Paytm webhook"})}};