import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class BrowserStorageService {
  constructor(@Inject(PLATFORM_ID) private platformId: Object) {}

  isBrowser(): boolean {
    return isPlatformBrowser(this.platformId);
  }

  getItem(key: string): string | null {
    if (!this.isBrowser()) {
      return null;
    }

    try {
      return localStorage.getItem(key);
    } catch {
      return null;
    }
  }

  setItem(key: string, value: string): void {
    if (!this.isBrowser()) {
      return;
    }

    try {
      localStorage.setItem(key, value);
    } catch {
      // Ignore storage errors in the browser.
    }
  }

  removeItem(key: string): void {
    if (!this.isBrowser()) {
      return;
    }

    try {
      localStorage.removeItem(key);
    } catch {
      // Ignore storage errors in the browser.
    }
  }

  getObject<T>(key: string, fallback: T): T {
    const raw = this.getItem(key);

    if (!raw) {
      return fallback;
    }

    try {
      return JSON.parse(raw) as T;
    } catch {
      return fallback;
    }
  }

  setObject(key: string, value: unknown): void {
    this.setItem(key, JSON.stringify(value));
  }
}
