import { Injectable } from '@angular/core';
import {
  DISABLED_DEFAULT_SERVER_KEYS_STORAGE_KEY,
  REMOVED_DEFAULT_SERVER_KEYS_STORAGE_KEY,
  SERVER_ENDPOINTS_STORAGE_KEY
} from '../constants/server-directory.infrastructure.constants';
import type { ServerEndpoint } from '../../domain/models/server-directory.model';

@Injectable({ providedIn: 'root' })
export class ServerEndpointStorageService {
  loadEndpoints(): ServerEndpoint[] | null {
    const stored = localStorage.getItem(SERVER_ENDPOINTS_STORAGE_KEY);

    if (!stored) {
      return null;
    }

    try {
      const parsed = JSON.parse(stored) as unknown;

      return Array.isArray(parsed)
        ? parsed as ServerEndpoint[]
        : null;
    } catch {
      return null;
    }
  }

  saveEndpoints(endpoints: ServerEndpoint[]): void {
    localStorage.setItem(SERVER_ENDPOINTS_STORAGE_KEY, JSON.stringify(endpoints));
  }

  loadDisabledDefaultEndpointKeys(): Set<string> {
    return this.loadStringSet(DISABLED_DEFAULT_SERVER_KEYS_STORAGE_KEY);
  }

  saveDisabledDefaultEndpointKeys(keys: Set<string>): void {
    this.saveStringSet(DISABLED_DEFAULT_SERVER_KEYS_STORAGE_KEY, keys);
  }

  clearDisabledDefaultEndpointKeys(): void {
    localStorage.removeItem(DISABLED_DEFAULT_SERVER_KEYS_STORAGE_KEY);
  }

  loadRemovedDefaultEndpointKeys(): Set<string> {
    return this.loadStringSet(REMOVED_DEFAULT_SERVER_KEYS_STORAGE_KEY);
  }

  saveRemovedDefaultEndpointKeys(keys: Set<string>): void {
    this.saveStringSet(REMOVED_DEFAULT_SERVER_KEYS_STORAGE_KEY, keys);
  }

  clearRemovedDefaultEndpointKeys(): void {
    localStorage.removeItem(REMOVED_DEFAULT_SERVER_KEYS_STORAGE_KEY);
  }

  private loadStringSet(storageKey: string): Set<string> {
    const stored = localStorage.getItem(storageKey);

    if (!stored) {
      return new Set<string>();
    }

    try {
      const parsed = JSON.parse(stored) as unknown;

      if (!Array.isArray(parsed)) {
        return new Set<string>();
      }

      return new Set(parsed.filter((value): value is string => typeof value === 'string'));
    } catch {
      return new Set<string>();
    }
  }

  private saveStringSet(storageKey: string, keys: Set<string>): void {
    if (keys.size === 0) {
      localStorage.removeItem(storageKey);
      return;
    }

    localStorage.setItem(storageKey, JSON.stringify([...keys]));
  }
}
