import { decryptData, encryptData } from '@pos/base';
import { ILocalStorageStorage, LSSetItemEntity } from './storage.interface';

export class LocalStorageService implements ILocalStorageStorage {
  storageKey?: string;
  constructor(storageKey?: string) {
    this.storageKey = storageKey;
  }

  create(payload: LSSetItemEntity): void {
    const keyData = this.storageKey ?? payload.key;
    if (keyData && payload.value) {
      const value = encryptData(JSON.stringify(payload.value));
      localStorage.setItem(keyData, value);
    }
  }

  get(key?: string): string | null | undefined {
    const keyData = this.storageKey ?? key;
    if (keyData) {
      const value = localStorage.getItem(keyData);
      if (value) return JSON.parse(decryptData(value));
      return undefined;
    }
  }

  delete(key?: string): void {
    const keyData = this.storageKey ?? key;
    if (keyData) localStorage.removeItem(keyData);
  }
}
