import type { SavedDevice } from "@/stores/media-devices-store";

/**
 * Resolves a saved device preference against the currently available
 * devices. Returns the saved `deviceId` only if it still appears in the
 * list — otherwise `undefined` so getUserMedia falls back to the
 * system default. This keeps "unplugged device" handling in one place.
 */
export function resolveEffectiveDeviceId(
  saved: SavedDevice | null,
  available: MediaDeviceInfo[],
): string | undefined {
  if (!saved) return undefined;
  const match = available.find((d) => d.deviceId === saved.deviceId);
  return match ? match.deviceId : undefined;
}

export function isSavedDeviceAvailable(
  saved: SavedDevice | null,
  available: MediaDeviceInfo[],
): boolean {
  if (!saved) return true;
  return available.some((d) => d.deviceId === saved.deviceId);
}
