import { Injectable } from '@angular/core';

const SESSION_STORAGE_KEY = 'metoyou.clientInstanceId';
const LEGACY_LOCAL_STORAGE_KEY = 'metoyou.clientInstanceId';

/**
 * Stable id for this browser tab/window session.
 *
 * Stored in sessionStorage so multiple tabs or synced browser profiles do not
 * share the same id and evict each other on the signaling server.
 */
@Injectable({ providedIn: 'root' })
export class ClientInstanceService {
  private cachedId: string | null = null;

  getClientInstanceId(): string {
    if (this.cachedId) {
      return this.cachedId;
    }

    const stored = this.readStoredId();

    if (stored) {
      this.cachedId = stored;
      return stored;
    }

    this.clearLegacyLocalStorageId();

    const created = crypto.randomUUID();

    this.writeStoredId(created);
    this.cachedId = created;

    return created;
  }

  private readStoredId(): string | null {
    try {
      const raw = sessionStorage.getItem(SESSION_STORAGE_KEY)?.trim();

      return raw || null;
    } catch {
      return null;
    }
  }

  private writeStoredId(id: string): void {
    try {
      sessionStorage.setItem(SESSION_STORAGE_KEY, id);
    } catch {
      // Ignore quota / private-mode failures; in-memory cache still works for this session.
    }
  }

  private clearLegacyLocalStorageId(): void {
    try {
      localStorage.removeItem(LEGACY_LOCAL_STORAGE_KEY);
    } catch {
      // Ignore storage access failures.
    }
  }
}
