"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"),publicUrl=process.env.NEXT_PUBLIC_SITE_URL,isProduction="production"===process.env.NODE_ENV;exports.metadata={summary:"Creates a 2Checkout payment session",description:"Initiates a 2Checkout payment process by creating a payment session. This endpoint supports hosted checkout integration for web applications.",operationId:"create2CheckoutPayment",tags:["Finance","Deposit"],logModule:"2CHECKOUT_DEPOSIT",logTitle:"Create 2Checkout payment session",requestBody:{description:"Payment information for 2Checkout",content:{"application/json":{schema:{type:"object",properties:{amount:{type:"number",description:"Payment amount in base currency unit"},currency:{type:"string",description:"Currency code (e.g., USD, EUR)"},customerInfo:{type:"object",description:"Customer billing information",properties:{firstName:{type:"string"},lastName:{type:"string"},email:{type:"string"},phone:{type:"string"},address:{type:"string"},city:{type:"string"},state:{type:"string"},zip:{type:"string"},country:{type:"string"}},required:["firstName","lastName","email","address","city","zip","country"]}},required:["amount","currency","customerInfo"]}}}},responses:{200:{description:"2Checkout payment session created successfully. Returns checkout URL for redirect.",content:{"application/json":{schema:{type:"object",properties:{checkoutUrl:{type:"string",description:"2Checkout hosted checkout URL"},orderReference:{type:"string",description:"Order reference for tracking"},sessionId:{type:"string",description:"2Checkout session ID"}}}}}},401:query_1.unauthorizedResponse,404:(0,query_1.notFoundMetadataResponse)("2Checkout"),500:query_1.serverErrorResponse},requiresAuth:!0};exports.default=async e=>{var t,r,o;const{user:s,body:n,ctx:i}=e;if(!s)throw(0,error_1.createError)({statusCode:401,message:"User not authenticated"});const{amount:c,currency:a,customerInfo:u}=n;null==i||i.step("Fetching payment gateway configuration");const p=await db_1.models.depositGateway.findOne({where:{alias:"2checkout",status:!0}});if(!p)throw(0,error_1.createError)({statusCode:404,message:"2Checkout gateway not found"});if(!(null===(t=p.currencies)||void 0===t?void 0:t.includes(a)))throw(0,error_1.createError)({statusCode:400,message:`Currency ${a} is not supported by 2Checkout`});const{fixedFee:d,percentageFee:y}=p;null==i||i.step("Calculating fees");const m=c*(y||0)/100+(d||0),h=c+m,l=(0,utils_1.use2Checkout)(),g=(0,utils_1.get2CheckoutApiUrl)(l.isProduction),C=`deposit_${s.id}_${Date.now()}`,f={Country:u.country,Currency:a,CustomerIP:"127.0.0.1",ExternalReference:C,Language:"en",Source:l.accountReference||"API",BillingDetails:{Address1:u.address,City:u.city,CountryCode:u.country,Email:u.email,FirstName:u.firstName,LastName:u.lastName,Phone:u.phone||"",State:u.state||"",Zip:u.zip},Items:[{Name:"Deposit",Description:`Deposit ${c} ${a}`,IsDynamic:!0,Tangible:!1,PurchaseType:"PRODUCT",Price:{Amount:c,Type:"FIXED"},Quantity:1}],PaymentDetails:{Type:"CC",Currency:a,CustomerIP:"127.0.0.1"}};m>0&&f.Items.push({Name:"Processing Fee",Description:`Processing fee for ${a} deposit`,IsDynamic:!0,Tangible:!1,PurchaseType:"PRODUCT",Price:{Amount:m,Type:"FIXED"},Quantity:1});try{const e=await fetch(`${g}/rest/6.0/orders/`,{method:"POST",headers:{"Content-Type":"application/json","X-Avangate-Authentication":`code="${l.merchantCode}" date="${(new Date).toISOString()}" hash=""`},body:JSON.stringify(f)}),t=await e.json();if(!e.ok||t.Errors)throw(0,error_1.createError)({statusCode:400,message:`2Checkout API error: ${(null===(o=null===(r=t.Errors)||void 0===r?void 0:r[0])||void 0===o?void 0:o.Message)||"Unknown error"}`});return{checkoutUrl:l.isProduction?`https://secure.2checkout.com/checkout/buy?merchant=${l.merchantCode}&tco-currency=${a}&tco-amount=${h}&external-reference=${C}`:`https://sandbox.2checkout.com/checkout/buy?merchant=${l.merchantCode}&tco-currency=${a}&tco-amount=${h}&external-reference=${C}`,orderReference:C,sessionId:t.RefNo||t.OrderNo}}catch(e){throw(0,error_1.createError)({statusCode:500,message:`Error creating 2Checkout session: ${e.message}`})}};