"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"),utils_1=require("./utils"),db_1=require("@b/db"),emails_1=require("@b/utils/emails"),console_1=require("@b/utils/console"),wallet_1=require("@b/services/wallet");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:"STRIPE_DEPOSIT",logTitle:"Verify and complete Stripe deposit",parameters:[{index:0,name:"sessionId",in:"query",description:"Stripe checkout session 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:{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)("Stripe"),500:query_1.serverErrorResponse}};exports.default=async e=>{var t;const{user:i,query:s,ctx:r}=e;if(!i)throw(0,error_1.createError)({statusCode:401,message:"User not authenticated"});const{sessionId:n}=s,a=(0,utils_1.useStripe)();try{null==r||r.step("Retrieving Stripe checkout session");const e=await a.checkout.sessions.retrieve(n),s=e.payment_intent,o=s?await a.paymentIntents.retrieve(s):null,c=(await a.checkout.sessions.listLineItems(n)).data.map(e=>({id:e.id,description:e.description,currency:e.currency,amount:e.amount_subtotal/100})),u=o?o.status:"unknown";if("succeeded"===u){null==r||r.step("Fetching user account");const s=await db_1.models.user.findByPk(i.id);null==r||r.step("Checking for duplicate transaction");if(await db_1.models.transaction.findOne({where:{referenceId:n}}))return{id:e.id,status:u,line_items:c};const{currency:a,amount:o}=c[0];null==r||r.step("Finding or creating wallet");const d=(await wallet_1.walletCreationService.getOrCreateWallet(i.id,"FIAT",a)).wallet;null==r||r.step("Validating currency");const l=await db_1.models.currency.findOne({where:{id:d.currency}});if(!l){null==r||r.fail("Currency not found");throw(0,error_1.createError)({statusCode:404,message:"Currency not found"})}null==r||r.step("Calculating fees");const p=(null===(t=c[1])||void 0===t?void 0:t.amount)||0;let m=d.balance;m+=Number(o);m=parseFloat(m.toFixed(l.precision||2));null==r||r.step("Starting database transaction");const y=await db_1.sequelize.transaction(async e=>{null==r||r.step("Updating wallet balance via wallet service");const t=`stripe_session_${n}`,s=await wallet_1.walletService.credit({idempotencyKey:t,userId:i.id,walletId:d.id,walletType:"FIAT",currency:a,amount:o,operationType:"DEPOSIT",referenceId:n,description:`Stripe deposit of ${o} ${a}`,metadata:{method:"STRIPE",sessionId:n,fee:p},transaction:e});if(p>0){null==r||r.step("Recording admin profit");await db_1.models.adminProfit.create({amount:p,currency:d.currency,type:"DEPOSIT",transactionId:s.transactionId,description:`Admin profit from Stripe deposit fee of ${p} ${d.currency} for user (${i.id})`},{transaction:e})}return s}),f=await db_1.models.transaction.findByPk(y.transactionId);try{null==r||r.step("Sending notification email");await(0,emails_1.sendFiatTransactionEmail)(s,f,a,m)}catch(e){console_1.logger.error("STRIPE","Error sending email",e)}}return{id:e.id,status:u,line_items:c}}catch(e){throw(0,error_1.createError)({statusCode:500,message:`Error retrieving session and line items: ${e.message}`})}};