/**
 * LocalStorage helpers with type safety and namespacing
 * @countermeasure/web-components/services/storage
 */

export interface StorageConfig {
  prefix?: string
}

const DEFAULT_PREFIX = 'tf_'

export class StorageManager {
  private readonly prefix: string

  constructor(config?: StorageConfig) {
    this.prefix = config?.prefix ?? DEFAULT_PREFIX
  }

  get(key: string): unknown {
    const fullKey = this.prefix + key
    try {
      const raw = localStorage.getItem(fullKey)
      if (raw === null) {
        return null
      }
      return JSON.parse(raw) as unknown
    } catch {
      return null
    }
  }

  set(key: string, value: unknown): void {
    const fullKey = this.prefix + key
    localStorage.setItem(fullKey, JSON.stringify(value))
  }

  remove(key: string): void {
    const fullKey = this.prefix + key
    localStorage.removeItem(fullKey)
  }

  has(key: string): boolean {
    const fullKey = this.prefix + key
    return localStorage.getItem(fullKey) !== null
  }

  clear(): void {
    const keysToRemove: string[] = []
    for (let i = 0; i < localStorage.length; i += 1) {
      const key = localStorage.key(i)
      if (key?.startsWith(this.prefix) === true) {
        keysToRemove.push(key)
      }
    }
    for (const key of keysToRemove) {
      localStorage.removeItem(key)
    }
  }

  getKeys(): string[] {
    const keys: string[] = []
    for (let i = 0; i < localStorage.length; i += 1) {
      const key = localStorage.key(i)
      if (key?.startsWith(this.prefix) === true) {
        keys.push(key.slice(this.prefix.length))
      }
    }
    return keys
  }
}

const defaultManager = new StorageManager()

export function storageGet(key: string): unknown {
  return defaultManager.get(key)
}

export function storageSet(key: string, value: unknown): void {
  defaultManager.set(key, value)
}

export function storageRemove(key: string): void {
  defaultManager.remove(key)
}

export function storageHas(key: string): boolean {
  return defaultManager.has(key)
}
