import CryptoJS from 'crypto-js'
const SECRET_KEY = import.meta.env.ENV_SECRET_KEY;
const URL_SECRET_KEY = import.meta.env.ENV_URL_SECRET_KEY;

export function encryptData(data, ENCRYPTION_KEY) {
    try {
        const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), ENCRYPTION_KEY).toString()
        return ciphertext
    } catch (error) {
        console.error('Error encrypting data (renderer):', error);
        return null
    }
}

export const decryptToObject=(encryptedUrlSafeStr) =>{
    try {
      if (!encryptedUrlSafeStr) return null;

      // Restore base64 format
      let base64 = encryptedUrlSafeStr
        .replace(/-/g, "+")
        .replace(/_/g, "/");

      // Add missing padding
      while (base64.length % 4 !== 0) {
        base64 += "=";
      }

      const bytes = CryptoJS.AES.decrypt(base64, SECRET_KEY);
      const decrypted = bytes.toString(CryptoJS.enc.Utf8);
      return JSON.parse(decrypted);
    } catch (err) {
      console.error("Decryption failed:", err);
      return null;
    }
  }
export function decryptData(encryptedData, ENCRYPTION_KEY) {
    try {
        const bytes = CryptoJS.AES.decrypt(encryptedData, ENCRYPTION_KEY)
        return JSON.parse(bytes.toString(CryptoJS.enc.Utf8))
    } catch (error) {
        console.error('Error decrypting data (renderer):', error)
        return null
    }
}

export function formatAmount(decimal, amount) {

    const parsedAmount = parseFloat(amount);
    if (isNaN(parsedAmount)) return decimal ? '0.00' : '0';

    return decimal ? parsedAmount.toFixed(2) : Math.round(parsedAmount).toString();
}


export const getAuthTokens = () => {

    return {
        accessToken: sessionStorage.getItem('auth'),
    };

};