import appConfig from 'src/config/app';

// Typescript高级类型Record
// https://zhuanlan.zhihu.com/p/356662885
type IWebStorageReturnType =
  | Date
  | RegExp
  | number
  | boolean
  | string
  | any[]
  | Record<string, any>
  | null;

interface IWebStorage {
  setItem: (key: string, value: any) => void;
  getItem: (key: string) => IWebStorageReturnType;
  removeItem: (key: string) => void;
}

const prefixKey = appConfig.storagePrefix;

function getStorage(type: 'local' | 'session'): IWebStorage {
  const webStorage =
    type === 'local' ? window.localStorage : window.sessionStorage;
  return {
    setItem: (key: string, value: any) => {
      webStorage.setItem(prefixKey + key, value);
    },
    getItem: (key: string) => {
      const item = webStorage.getItem(prefixKey + key);
      return item || null;
    },
    removeItem: (key: string) => {
      webStorage.removeItem(prefixKey + key);
    },
  };
}
export type { IWebStorage, IWebStorageReturnType };
export { getStorage };
