"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"),console_1=require("@b/utils/console"),db_1=require("@b/db"),utils_1=require("./utils");exports.metadata={summary:"Create Authorize.Net hosted payment page",description:"Creates an Authorize.Net Accept Hosted payment page for secure deposit processing. Returns a payment token for hosted payment form integration.",operationId:"createAuthorizeNetPayment",tags:["Finance","Deposit"],requiresAuth:!0,logModule:"AUTHORIZENET_DEPOSIT",logTitle:"Create Authorize.Net payment",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{amount:{type:"number",description:"Deposit amount"},currency:{type:"string",description:"Currency code (USD, CAD, EUR, etc.)",example:"USD"}},required:["amount","currency"]}}}},responses:{200:{description:"Hosted payment page created successfully. Returns payment token and form URL.",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:{token:{type:"string",description:"Payment token for hosted form"},formUrl:{type:"string",description:"URL for hosted payment form"},referenceId:{type:"string",description:"Transaction reference ID"}}}}}}}},401:query_1.unauthorizedResponse,404:(0,query_1.notFoundMetadataResponse)("Authorize.Net"),500:query_1.serverErrorResponse}};exports.default=async e=>{const{user:t,body:r,ctx:o}=e;if(!(null==t?void 0:t.id))throw(0,error_1.createError)({statusCode:401,message:"User not authenticated"});null==o||o.step("Fetching user account");const s=await db_1.models.user.findByPk(t.id);if(!s)throw(0,error_1.createError)({statusCode:404,message:"User not found"});const{amount:a,currency:n}=r;if(!a||a<=0)throw(0,error_1.createError)({statusCode:400,message:"Invalid amount"});if(!["USD","CAD","GBP","EUR","AUD","NZD","DKK","NOK","PLN","SEK"].includes(n))throw(0,error_1.createError)({statusCode:400,message:`Currency ${n} is not supported by Authorize.Net`});const i=await db_1.models.depositGateway.findOne({where:{name:"AUTHORIZENET"}});if(!i)throw(0,error_1.createError)({statusCode:404,message:"Authorize.Net gateway not found"});if(!i.status)throw(0,error_1.createError)({statusCode:400,message:"Authorize.Net gateway is currently disabled"});if(!i.currencies.includes(n))throw(0,error_1.createError)({statusCode:400,message:`Currency ${n} is not supported by this gateway`});if(a<(i.minAmount||1))throw(0,error_1.createError)({statusCode:400,message:`Minimum deposit amount is ${i.minAmount||1} ${n}`});if(a>(i.maxAmount||1e4))throw(0,error_1.createError)({statusCode:400,message:`Maximum deposit amount is ${i.maxAmount||1e4} ${n}`});try{const e=(0,utils_1.getAuthorizeNetConfig)();null==o||o.step("Calculating fees");const r=i.fixedFee||0,u=i.percentageFee||0,c=Number((a*u/100+r).toFixed(2)),d=Number((a+c).toFixed(2)),m=`deposit_${t.id.toString()}_${Date.now()}`;null==o||o.step("Creating transaction record");await db_1.models.transaction.create({userId:t.id,type:"DEPOSIT",amount:a,fee:c,referenceId:m,status:"PENDING",description:`Authorize.Net deposit of ${a} ${n}`,metadata:JSON.stringify({method:"AUTHORIZENET",currency:n,totalAmount:d})});const p={merchantAuthentication:{name:e.apiLoginId,transactionKey:e.transactionKey},refId:m,transactionRequest:{transactionType:"authCaptureTransaction",amount:d.toString(),currencyCode:n,customer:{id:t.id.toString(),email:s.email},billTo:{firstName:s.firstName||"",lastName:s.lastName||""},order:{invoiceNumber:m,description:`Deposit to wallet - ${a} ${n}`}},hostedPaymentSettings:(0,utils_1.generateHostedPaymentSettings)({returnUrl:`${process.env.FRONTEND_URL}/finance/deposit?status=success&ref=${m}`,cancelUrl:`${process.env.FRONTEND_URL}/finance/deposit?status=cancelled&ref=${m}`,showReceipt:!1})},l=(await(0,utils_1.makeAuthorizeNetRequest)({getHostedPaymentPageRequest:p},e)).getHostedPaymentPageResponse;if("Ok"!==l.messages.resultCode){const e=l.messages.message.map(e=>e.text).join(", ");throw(0,error_1.createError)({statusCode:400,message:`Authorize.Net error: ${e}`})}if(!l.token)throw(0,error_1.createError)({statusCode:500,message:"Failed to create hosted payment page - no token received"});const y=`https://${"production"===e.environment?"accept":"test"}.authorize.net/payment/payment?token=${l.token}`;return{status:!0,statusCode:200,data:{token:l.token,formUrl:y,referenceId:m,amount:a,currency:n,fee:c,totalAmount:d}}}catch(e){console_1.logger.error("AUTHORIZENET","Payment creation error",e);throw(0,error_1.createError)({statusCode:500,message:e instanceof Error?e.message:"Failed to create Authorize.Net payment"})}};