import type { TrackRef } from '$lib/api/types';

export type PersistedPlayerState = {
  v: 1;
  queue: TrackRef[];
  index: number;
  position: number;
  savedAt: number;
};

const persistKey = (userId: string) => `minstrel.queue.${userId}`;

export function readPersistedQueue(userId: string): PersistedPlayerState | null {
  if (typeof localStorage === 'undefined') return null;
  try {
    const raw = localStorage.getItem(persistKey(userId));
    if (!raw) return null;
    const parsed = JSON.parse(raw) as Partial<PersistedPlayerState>;
    if (parsed.v !== 1) return null;
    if (!Array.isArray(parsed.queue)) return null;
    if (typeof parsed.index !== 'number') return null;
    if (typeof parsed.position !== 'number') return null;
    return parsed as PersistedPlayerState;
  } catch {
    return null;
  }
}

export function writePersistedQueue(
  userId: string,
  state: { queue: TrackRef[]; index: number; position: number }
): void {
  if (typeof localStorage === 'undefined') return;
  try {
    const payload: PersistedPlayerState = {
      v: 1,
      queue: state.queue,
      index: state.index,
      position: state.position,
      savedAt: Date.now()
    };
    localStorage.setItem(persistKey(userId), JSON.stringify(payload));
  } catch {
    // QuotaExceededError, security errors, etc. Swallow; persistence is best-effort.
  }
}

export function clearPersistedQueue(userId: string): void {
  if (typeof localStorage === 'undefined') return;
  try {
    localStorage.removeItem(persistKey(userId));
  } catch {
    /* ignore */
  }
}
