import type { TrackRef, PlaylistDetail } from '$lib/api/types';
import { systemShuffle, getPlaylist } from '$lib/api/playlists';
import { playlistTrackToRef } from './playlistTrackToRef';

// #968: builds the self-heal closure for a system-playlist queue. On total
// playback failure (every queued track unplayable — typically a stale tab
// left open across the daily rebuild) the player calls this to re-pull the
// current snapshot and resume.
//
// Single-instance variants (for_you, discover, deep_cuts, …) re-pull by
// variant via the rotation-aware shuffle endpoint. Per-artist mixes
// (songs_like_artist — one playlist per seed artist) can't be addressed by
// variant alone, so they re-pull by playlist id. Mirrors the play routing
// in PlaylistCard.

function toRefs(detail: PlaylistDetail): TrackRef[] {
  return detail.tracks
    .map((r) => playlistTrackToRef(r))
    .filter((t): t is TrackRef => t !== null);
}

export function systemPlaylistRefetch(opts: {
  variant: string;
  playlistId: string;
  perArtist: boolean;
}): () => Promise<TrackRef[]> {
  return async () => {
    const detail = opts.perArtist
      ? await getPlaylist(opts.playlistId)
      : await systemShuffle(opts.variant);
    return toRefs(detail);
  };
}
