"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const error_1=require("@b/utils/error"),db_1=require("@b/db"),emails_1=require("@b/utils/emails"),utils_1=require("./utils"),console_1=require("@b/utils/console"),wallet_1=require("@b/services/wallet");exports.metadata={summary:"Handles Mollie webhook notifications",description:"Processes payment status updates from Mollie backend notifications",operationId:"mollieWebhook",tags:["Finance","Deposit","Mollie","Webhook"],logModule:"WEBHOOK",logTitle:"Mollie webhook",requiresAuth:!1,requestBody:{required:!0,content:{"application/x-www-form-urlencoded":{schema:{type:"object",properties:{id:{type:"string",description:"Mollie payment ID"}},required:["id"]}}}},responses:{200:{description:"Webhook processed successfully",content:{"text/plain":{schema:{type:"string",example:"OK"}}}},400:{description:"Bad request"},404:{description:"Payment not found"},500:{description:"Internal server error"}}};exports.default=async e=>{var t,a,o,i,r;const{body:s}=e;if(!s.id)throw(0,error_1.createError)({statusCode:400,message:"Payment ID is required"});(0,utils_1.validateMollieConfig)();try{const e=s.id,r=await(0,utils_1.makeApiRequest)(`/payments/${e}`);if(!r)throw(0,error_1.createError)({statusCode:404,message:"Payment not found at Mollie"});const n=await db_1.models.transaction.findOne({where:{referenceId:e}});if(!n){if(!await db_1.models.transaction.findOne({where:{metadata:{molliePaymentId:e}}})){console_1.logger.warn("MOLLIE",`No transaction found for Mollie payment ID: ${e}`);return"OK"}}const l=n||await db_1.models.transaction.findOne({where:{metadata:{molliePaymentId:e}}});if((null===(t=l.metadata)||void 0===t?void 0:t.mollieStatus)===r.status)return"OK";const d=(0,utils_1.mapMollieStatus)(r.status),u=await db_1.models.user.findByPk(l.userId);if(!u){console_1.logger.error("MOLLIE",`User not found for transaction: ${l.uuid}`);return"OK"}if("paid"===r.status&&"COMPLETED"!==l.status){await db_1.sequelize.transaction(async t=>{var a;await db_1.models.transaction.update({status:"COMPLETED",referenceId:r.id,metadata:JSON.stringify({...l.metadata,molliePaymentId:r.id,mollieStatus:r.status,paymentMethod:r.method||"unknown",paidAt:r.createdAt,settlementAmount:r.settlementAmount,webhookProcessedAt:(new Date).toISOString()})},{where:{uuid:l.uuid},transaction:t});const o=(null===(a=l.metadata)||void 0===a?void 0:a.currency)||"EUR",i=(await wallet_1.walletCreationService.getOrCreateWallet(u.id,"FIAT",o,t)).wallet,s=`mollie_webhook_${e}`;await wallet_1.walletService.credit({idempotencyKey:s,userId:u.id,walletId:i.id,walletType:"FIAT",currency:o,amount:l.amount,operationType:"DEPOSIT",referenceId:e,description:`Mollie deposit - ${l.amount} ${o}`,metadata:{method:"MOLLIE",molliePaymentId:r.id,paymentMethod:r.method||"unknown"},transaction:t});if(r.settlementAmount&&r.amount){const e=(0,utils_1.parseMollieAmount)(r.amount.value,r.amount.currency)-(0,utils_1.parseMollieAmount)(r.settlementAmount.value,r.settlementAmount.currency);e>0&&await db_1.models.transaction.update({fee:e/100},{where:{uuid:l.uuid},transaction:t})}});try{const e=(null===(a=l.metadata)||void 0===a?void 0:a.currency)||"EUR",t=await db_1.models.wallet.findOne({where:{userId:u.id,currency:e,type:"FIAT"}});await(0,emails_1.sendFiatTransactionEmail)(u,{id:l.uuid,type:"DEPOSIT",amount:l.amount,status:"COMPLETED",description:`Mollie deposit - ${l.amount} ${e}`},e,(null==t?void 0:t.balance)||0)}catch(e){console_1.logger.error("MOLLIE","Failed to send confirmation email",e)}}else if(["failed","canceled","expired"].includes(r.status)){await db_1.models.transaction.update({status:d,metadata:JSON.stringify({...l.metadata,molliePaymentId:r.id,mollieStatus:r.status,failureReason:(null===(o=r.details)||void 0===o?void 0:o.failureReason)||"Payment failed",webhookProcessedAt:(new Date).toISOString()})},{where:{uuid:l.uuid}});try{const e=(null===(i=l.metadata)||void 0===i?void 0:i.currency)||"EUR";await(0,emails_1.sendFiatTransactionEmail)(u,{id:l.uuid,type:"DEPOSIT",amount:l.amount,status:d,description:`Mollie deposit failed - ${l.amount} ${e}`},e,0)}catch(e){console_1.logger.error("MOLLIE","Failed to send failure notification email",e)}}else await db_1.models.transaction.update({metadata:JSON.stringify({...l.metadata,molliePaymentId:r.id,mollieStatus:r.status,webhookProcessedAt:(new Date).toISOString()})},{where:{uuid:l.uuid}});console_1.logger.success("MOLLIE",`Webhook processed: Payment ${e} status ${r.status}`);return"OK"}catch(e){console_1.logger.error("MOLLIE","Webhook processing error",e);if(null===(r=e.message)||void 0===r?void 0:r.includes("API key"))throw(0,error_1.createError)({statusCode:500,message:"Configuration error"});return"OK"}};