import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

@Injectable({
  providedIn: 'root',
})
export class StorageService {
  getToken(): string | null {
    return localStorage.getItem(environment.tokenStorageKey);
  }

  setToken(token: string): void {
    localStorage.setItem(environment.tokenStorageKey, token);
  }

  removeToken(): void {
    localStorage.removeItem(environment.tokenStorageKey);
  }

  getRefreshToken(): string | null {
    return localStorage.getItem(environment.refreshTokenStorageKey);
  }

  setRefreshToken(token: string): void {
    localStorage.setItem(environment.refreshTokenStorageKey, token);
  }

  removeRefreshToken(): void {
    localStorage.removeItem(environment.refreshTokenStorageKey);
  }

  getUser<T>(): T | null {
    const user = localStorage.getItem(environment.userStorageKey);
    if (user) {
      try {
        return JSON.parse(user) as T;
      } catch {
        return null;
      }
    }
    return null;
  }

  setUser<T>(user: T): void {
    localStorage.setItem(environment.userStorageKey, JSON.stringify(user));
  }

  removeUser(): void {
    localStorage.removeItem(environment.userStorageKey);
  }

  clear(): void {
    this.removeToken();
    this.removeRefreshToken();
    this.removeUser();
  }

  get<T>(key: string): T | null {
    const item = localStorage.getItem(key);
    if (item) {
      try {
        return JSON.parse(item) as T;
      } catch {
        return item as unknown as T;
      }
    }
    return null;
  }

  set(key: string, value: unknown): void {
    if (typeof value === 'string') {
      localStorage.setItem(key, value);
    } else {
      localStorage.setItem(key, JSON.stringify(value));
    }
  }

  remove(key: string): void {
    localStorage.removeItem(key);
  }
}
