/**
 * Device ID Management Service
 *
 * Manages device identification for Jellyfin server communication.
 * The Rust backend handles UUID generation and persistent storage in the database.
 * This service provides a simple interface with in-memory caching.
 *
 * TRACES: UR-009 | DR-011
 */

import { commands } from "$lib/api/bindings";

let cachedDeviceId: string | null = null;

/**
 * Get or create the device ID.
 * Device ID is a UUID v4 that persists across app restarts.
 * On first call, the Rust backend generates and stores a new UUID.
 * On subsequent calls, the stored UUID is retrieved.
 *
 * @returns The device ID string (UUID v4)
 *
 * TRACES: UR-009 | DR-011
 */
export async function getDeviceId(): Promise<string> {
  // Return cached value if available
  if (cachedDeviceId) {
    return cachedDeviceId;
  }

  try {
    // Rust backend handles generation and storage atomically
    const deviceId = await commands.deviceGetId();
    cachedDeviceId = deviceId;
    return deviceId;
  } catch (e) {
    console.error("[deviceId] Failed to get device ID from backend:", e);
    throw new Error("Failed to initialize device ID: " + String(e));
  }
}

/**
 * Get cached device ID synchronously (if available)
 * This should only be used after initial getDeviceId() call
 *
 * @returns The cached device ID, or empty string if not yet initialized
 */
export function getDeviceIdSync(): string {
  return cachedDeviceId || "";
}

/**
 * Clear cached device ID (for testing or logout scenarios)
 */
export function clearCache(): void {
  cachedDeviceId = null;
}
