"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const error_1=require("@b/utils/error"),db_1=require("@b/db"),utils_1=require("./utils"),{OrderRequest:OrderRequest,CheckoutPaymentIntent:CheckoutPaymentIntent,ItemCategory:ItemCategory}=require("@paypal/paypal-server-sdk"),query_1=require("@b/utils/query"),publicUrl=process.env.NEXT_PUBLIC_SITE_URL,isProduction="production"===process.env.NODE_ENV,siteName=process.env.NEXT_PUBLIC_SITE_NAME;exports.metadata={summary:"Creates a PayPal payment",description:"Initiates a PayPal payment process by creating a new order.",operationId:"createPayPalPayment",tags:["Finance","Deposit"],logModule:"PAYPAL_DEPOSIT",logTitle:"Create PayPal payment",requestBody:{description:"Payment information and application type",content:{"application/json":{schema:{type:"object",properties:{amount:{type:"number",description:"Payment amount in smallest currency unit (e.g., cents)"},currency:{type:"string",description:"Currency code (e.g., USD)"}},required:["amount","currency"]}}}},responses:(0,query_1.createRecordResponses)("PayPal Order"),requiresAuth:!0};exports.default=async e=>{const{user:t,body:r,ctx:a}=e;if(!(null==t?void 0:t.id))throw(0,error_1.createError)({statusCode:401,message:"Unauthorized"});const{amount:o,currency:n}=r;null==a||a.step("Fetching payment gateway configuration");const s=await db_1.models.depositGateway.findOne({where:{alias:"paypal",status:!0}});if(!s){null==a||a.fail("Payment gateway not found");throw(0,error_1.createError)({statusCode:404,message:"PayPal gateway not found"})}null==a||a.step("Calculating fees");const i=s.fixedFee||0,u=s.percentageFee||0,c=Math.max(parseFloat(o)*u/100+i,0),l=parseFloat(o)-c;if(l<0)throw(0,error_1.createError)({statusCode:400,message:"Invalid amount"});const d=parseFloat(o).toFixed(2),p={intent:CheckoutPaymentIntent.Capture,purchaseUnits:[{amount:{currencyCode:n,value:d,breakdown:{itemTotal:{currencyCode:n,value:l.toFixed(2)},taxTotal:{currencyCode:n,value:c.toFixed(2)}}},items:[{name:"Deposit",unitAmount:{currencyCode:n,value:l.toFixed(2)},quantity:"1",category:ItemCategory.DigitalGoods}]}],paymentSource:{paypal:{experienceContext:{brandName:siteName,returnUrl:`${publicUrl}${isProduction?"":":3000"}/finance/deposit/paypal`,cancelUrl:`${publicUrl}${isProduction?"":":3000"}/finance/deposit`}}}};try{const e=(0,utils_1.paypalOrdersController)();null==a||a.step("Creating PayPal order");const{result:t}=await e.createOrder({body:p});return{id:t.id,links:t.links}}catch(e){throw(0,error_1.createError)({statusCode:500,message:`Error creating PayPal order: ${e.message}`})}};