import { Injectable } from '@angular/core';
import { jsonStorage } from '../../../../infrastructure/persistence/json-storage.service';
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 {
  private readonly storage = jsonStorage;

  loadEndpoints(): ServerEndpoint[] | null {
    const parsed = this.storage.read<unknown>(SERVER_ENDPOINTS_STORAGE_KEY, null);

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

  saveEndpoints(endpoints: ServerEndpoint[]): void {
    this.storage.write(SERVER_ENDPOINTS_STORAGE_KEY, 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 {
    this.storage.remove(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 {
    this.storage.remove(REMOVED_DEFAULT_SERVER_KEYS_STORAGE_KEY);
  }

  private loadStringSet(storageKey: string): Set<string> {
    const parsed = this.storage.read<unknown>(storageKey, null);

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

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

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

    this.storage.write(storageKey, [...keys]);
  }
}
