import { persistPermanentStorageObjects } from './persistPermanentStorageObjects';

const browserStorage = typeof window !== 'undefined' ? window.localStorage : null;

export const setBrowserStorageItem = (item: string, data: string) => browserStorage?.setItem(item, data);

export const getBrowserStorageItem = (item: string) => browserStorage?.getItem(item) ?? null;

export const removeBrowserStorageItem = (item: string) => browserStorage?.removeItem(item);

export const clearBrowserStorage = () => browserStorage?.clear();

const storage: { [key: string]: string | null } = {};

export const setStorageItem = (item: string, data: string) => {
  storage[item] = data;
};

export const getStorageItem = (item: string) => storage[item] || getBrowserStorageItem(item) || null;

export const removeStorageItem = (item: string) => {
  storage[item] = null;
  removeBrowserStorageItem(item);
};

const deleteStorageKeys = () => {
  Object.keys(storage).forEach((item) => {
    delete storage[item];
  });
  clearBrowserStorage();
};

export const clearStorage = () => {
  persistPermanentStorageObjects(deleteStorageKeys);
};

const sessionStorage = typeof window !== 'undefined' ? window.sessionStorage : null;

export const setSessionStorageItem = (item: string, data: string) => sessionStorage?.setItem(item, data);

export const getSessionStorageItem = (item: string) => sessionStorage?.getItem(item) ?? null;

export const removeSessionStorageItem = (item: string) => sessionStorage?.removeItem(item);

export const clearSessionStorage = () => sessionStorage?.clear();

export default storage;
