"use strict";var __importDefault=this&&this.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(exports,"__esModule",{value:!0});exports.generateKlarnaReference=exports.convertFromKlarnaAmount=exports.convertToKlarnaAmount=exports.verifyKlarnaWebhookSignature=exports.KlarnaError=exports.KLARNA_LOCALE_MAP=exports.KLARNA_COUNTRY_CURRENCY_MAP=exports.KLARNA_FRAUD_STATUS=exports.KLARNA_ORDER_STATUS=exports.KLARNA_STATUS_MAPPING=exports.KLARNA_PAYMENT_CATEGORIES=exports.validateCurrency=exports.makeKlarnaRequest=exports.getKlarnaConfig=void 0;const crypto_1=__importDefault(require("crypto")),error_1=require("@b/utils/error"),getKlarnaConfig=()=>{const r=process.env.APP_KLARNA_USERNAME,e=process.env.APP_KLARNA_PASSWORD,t="production"===process.env.NODE_ENV;if(!r||!e)throw(0,error_1.createError)({statusCode:503,message:"Klarna credentials are not properly configured in environment variables"});return{username:r,password:e,baseUrl:t?"https://api.klarna.com":"https://api.playground.klarna.com",version:"1.0",region:"eu"}};exports.getKlarnaConfig=getKlarnaConfig;const makeKlarnaRequest=async(r,e="POST",t)=>{const a=(0,exports.getKlarnaConfig)(),o=`${a.baseUrl}${r}`,n={method:e,headers:{"Content-Type":"application/json",Authorization:`Basic ${Buffer.from(`${a.username}:${a.password}`).toString("base64")}`,"User-Agent":"Klarna-API-Client/1.0",Accept:"application/json"}};!t||"POST"!==e&&"PUT"!==e&&"PATCH"!==e||(n.body=JSON.stringify(t));try{const r=await fetch(o,n);if(!r.ok){const e=await r.text();let t=`Klarna API Error: ${r.status}`;try{const r=JSON.parse(e);t=r.error_message||r.message||t}catch(r){t=e||t}throw new KlarnaError(t,r.status,{response:e})}const e=r.headers.get("content-type");return e&&e.includes("application/json")?await r.json():await r.text()}catch(r){if(r instanceof KlarnaError)throw r;throw new KlarnaError("Network error occurred",500,{message:r.message})}};exports.makeKlarnaRequest=makeKlarnaRequest;const validateCurrency=r=>["USD","EUR","GBP","SEK","NOK","DKK","AUD","CAD","CHF","CZK","PLN","RON","NZD"].includes(r.toUpperCase());exports.validateCurrency=validateCurrency;exports.KLARNA_PAYMENT_CATEGORIES={PAY_NOW:"pay_now",PAY_LATER:"pay_later",PAY_OVER_TIME:"pay_over_time",SLICE_IT:"slice_it"};exports.KLARNA_STATUS_MAPPING={AUTHORIZED:"PENDING",PART_CAPTURED:"PENDING",CAPTURED:"COMPLETED",CANCELLED:"CANCELLED",EXPIRED:"FAILED",CLOSED:"FAILED"};exports.KLARNA_ORDER_STATUS={AUTHORIZED:"AUTHORIZED",PART_CAPTURED:"PART_CAPTURED",CAPTURED:"CAPTURED",CANCELLED:"CANCELLED",EXPIRED:"EXPIRED",CLOSED:"CLOSED"};exports.KLARNA_FRAUD_STATUS={ACCEPTED:"ACCEPTED",PENDING:"PENDING",REJECTED:"REJECTED"};exports.KLARNA_COUNTRY_CURRENCY_MAP={US:["USD"],GB:["GBP"],DE:["EUR"],SE:["SEK"],NO:["NOK"],DK:["DKK"],FI:["EUR"],NL:["EUR"],AT:["EUR"],CH:["CHF"],BE:["EUR"],FR:["EUR"],IT:["EUR"],ES:["EUR"],PL:["PLN"],CZ:["CZK"],AU:["AUD"],NZ:["NZD"],CA:["CAD"],RO:["RON"]};exports.KLARNA_LOCALE_MAP={US:"en-US",GB:"en-GB",DE:"de-DE",SE:"sv-SE",NO:"nb-NO",DK:"da-DK",FI:"fi-FI",NL:"nl-NL",AT:"de-AT",CH:"de-CH",BE:"nl-BE",FR:"fr-FR",IT:"it-IT",ES:"es-ES",PL:"pl-PL",CZ:"cs-CZ",AU:"en-AU",NZ:"en-NZ",CA:"en-CA",RO:"ro-RO"};class KlarnaError extends Error{constructor(r,e=500,t={}){super(r);this.name="KlarnaError";this.statusCode=e;this.details=t}}exports.KlarnaError=KlarnaError;const verifyKlarnaWebhookSignature=(r,e,t)=>{try{const a=e.split(",");let o="",n="";a.forEach(r=>{const[e,t]=r.split("=");"ts"===e&&(o=t);"sig"===e&&(n=t)});if(!o||!n)return!1;const s=crypto_1.default.createHmac("sha512",t).update(r).digest("hex");return crypto_1.default.timingSafeEqual(Buffer.from(n,"hex"),Buffer.from(s,"hex"))}catch(r){return!1}};exports.verifyKlarnaWebhookSignature=verifyKlarnaWebhookSignature;const convertToKlarnaAmount=r=>Math.round(100*r);exports.convertToKlarnaAmount=convertToKlarnaAmount;const convertFromKlarnaAmount=r=>r/100;exports.convertFromKlarnaAmount=convertFromKlarnaAmount;const generateKlarnaReference=()=>`KLR-${Date.now().toString()}-${Math.random().toString(36).substring(2,8)}`.toUpperCase();exports.generateKlarnaReference=generateKlarnaReference;