import { decryptData, encryptData } from './others'
import CryptoJS from 'crypto-js';

const SECRET_KEY = import.meta.env.ENV_SECRET_KEY

export const setSessionData = (key, value) => {
    try {
        const encryptedValue = encryptData(value, SECRET_KEY).toString()
        sessionStorage.setItem(key, encryptedValue)
    } catch (err) {
        console.error(`Error setting session data for key "${key}":`, err)
    }
}

// export const getSessionData = (key) => {
//     const data = sessionStorage.getItem(key)
//     if (data) {
//         try {
//             const decrypted = decryptData(data, SECRET_KEY)
//             return decrypted
//         } catch (err) {
//             console.error(`Error decrypting session data for key "${key}":`, err)
//         }
//     }
//     return null
// }

export const getSession = (key) => {
  const val = sessionStorage.getItem(key);
  if (val) {
    const decrypted = CryptoJS.AES.decrypt(val, SECRET_KEY).toString(
      CryptoJS.enc.Utf8
    );

    if (decrypted) {
      return JSON.parse(decrypted);
    }
  }
};

export const sessionStore = (key, value) => {
    const encryptedValue = CryptoJS.AES.encrypt(
        JSON.stringify(value),
        SECRET_KEY
    ).toString();

    if (encryptedValue) sessionStorage.setItem(key, encryptedValue);
};
export const clearSessionData = (key) => {
    sessionStorage.removeItem(key)
}

export const getAllSessionData = () => {
    const data = {}
    for (let i = 0; i < sessionStorage.length; i++) {
        const key = sessionStorage.key(i)
        const value = sessionStorage.getItem(key)
        try {
            const decrypted = decryptData(value, SECRET_KEY)
            data[key] = decrypted
        } catch (err) {
            console.error(`Error decrypting value for key "${key}":`, err)
            data[key] = null
        }
    }
    return data
}

export const getSessionKeys = (keys = []) => {
    const result = {}
    keys.forEach((key) => {
        const value = sessionStorage.getItem(key)
        try {
            const decrypted = decryptData(value, SECRET_KEY)
            result[key] = decrypted
        } catch (err) {
            console.error(`Error decrypting key "${key}":`, err)
            result[key] = null
        }
    })
    return result
}

export const clearAllSessionData = () => {
    sessionStorage.clear()
}

export const hasSessionKey = (key) => {
    return sessionStorage.getItem(key) !== null || sessionStorage.getItem(key) !== undefined
}