"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const query_1=require("@b/utils/query"),error_1=require("@b/utils/error"),emails_1=require("@b/utils/emails"),db_1=require("@b/db"),utils_1=require("./utils"),console_1=require("@b/utils/console"),utils_2=require("@b/api/finance/utils");exports.metadata={summary:"Verifies a Stripe checkout session",description:"Confirms the validity of a Stripe checkout session by its session ID, ensuring the session is authenticated and retrieving associated payment intent and line items details.",operationId:"verifyStripeCheckoutSession",tags:["Finance","Deposit"],requiresAuth:!0,logModule:"PAYPAL_DEPOSIT",logTitle:"Verify PayPal order",parameters:[{name:"orderId",in:"query",description:"The PayPal order ID",required:!0,schema:{type:"string"}}],responses:{200:{description:"Checkout session verified successfully. Returns the session ID, payment intent status, and detailed line items.",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the request was successful"},statusCode:{type:"number",description:"HTTP status code",example:200},data:{type:"object",properties:{id:{type:"string",description:"Session ID"},status:{type:"string",description:"Payment intent status",nullable:!0},lineItems:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Line item ID"},description:{type:"string",description:"Line item description"},amountSubtotal:{type:"number",description:"Subtotal amount"},amountTotal:{type:"number",description:"Total amount"},currency:{type:"string",description:"Currency code"}}},description:"List of line items associated with the checkout session"}}}}}}}},401:query_1.unauthorizedResponse,404:(0,query_1.notFoundMetadataResponse)("Paypal"),500:query_1.serverErrorResponse}};exports.default=async e=>{var t,r,s;const{user:i,query:a,ctx:n}=e;if(!(null==i?void 0:i.id))throw(0,error_1.createError)({statusCode:401,message:"User not authenticated"});null==n||n.step("Fetching user account");const o=await db_1.models.user.findByPk(i.id);if(!o)throw(0,error_1.createError)({statusCode:404,message:"User not found"});const{orderId:u}=a;null==n||n.step("Checking for duplicate transaction");if(await db_1.models.transaction.findOne({where:{referenceId:u}})){null==n||n.warn("Transaction already exists");throw(0,error_1.createError)({statusCode:409,message:"Transaction already exists"})}const c=(0,utils_1.paypalOrdersController)();try{const{result:e}=await c.captureOrder({id:u});if(!e.purchaseUnits||0===e.purchaseUnits.length)throw(0,error_1.createError)({statusCode:400,message:"No purchase units found in capture details."});const a=null===(t=e.purchaseUnits[0].payments)||void 0===t?void 0:t.captures;if(!a||0===a.length)throw(0,error_1.createError)({statusCode:400,message:"No captures found in purchase unit."});const d=a[0],l=parseFloat((null===(r=d.amount)||void 0===r?void 0:r.value)||"0"),p=(null===(s=d.amount)||void 0===s?void 0:s.currencyCode)||"";null==n||n.step("Fetching payment gateway configuration");const y=await db_1.models.depositGateway.findOne({where:{name:"PAYPAL"}});if(!y){null==n||n.fail("Payment gateway not found");throw(0,error_1.createError)({statusCode:404,message:"PayPal gateway not found"})}null==n||n.step("Validating currency");const m=await db_1.models.currency.findOne({where:{id:p}});if(!m){null==n||n.fail("Currency not found");throw(0,error_1.createError)({statusCode:404,message:"Currency not found"})}null==n||n.step("Calculating fees");const f=y.fixedFee||0,h=y.percentageFee||0,g=Number((l*h/100+f).toFixed(m.precision||2)),P=await(0,utils_2.processFiatDeposit)({userId:i.id,currency:p,amount:l,fee:g,referenceId:u,method:"PAYPAL",description:`Deposit of ${l-g} ${p} to ${o.firstName} ${o.lastName} wallet by PayPal.`,metadata:{currency:p},idempotencyKey:`paypal_deposit_${u}`,ctx:n}),_=await db_1.models.transaction.findByPk(P.transactionId);try{null==n||n.step("Sending notification email");await(0,emails_1.sendFiatTransactionEmail)(o,_,p,P.newBalance)}catch(e){console_1.logger.error("PAYPAL","Error sending email",e)}null==n||n.success("Paypal deposit completed successfully");return{transaction:_,balance:P.newBalance.toFixed(2),currency:p,method:"PAYPAL"}}catch(e){console_1.logger.error("PAYPAL","Error verifying PayPal order",e);throw(0,error_1.createError)({statusCode:500,message:`Error verifying PayPal order: ${e.message}`})}};