import { apiFetch } from '$lib/api/client';

export type RemoveTrackResult = {
  deleted_track_id: string;
  deleted_album_id?: string;
  deleted_artist_id?: string;
  /** Only present (always `true` when set) when the operator requested
   * unmonitor=true AND the Lidarr unmonitor call failed. The destructive
   * file + DB delete already succeeded — surface a follow-up toast so
   * the operator knows to manually unmonitor in Lidarr. */
  lidarr_unmonitor_failed?: true;
};

export type RemoveTrackOptions = {
  /** When true, after the file + DB delete the server calls
   * Lidarr.UnmonitorTrack so Lidarr won't search for a replacement.
   * When false / omitted, no Lidarr call — Lidarr's monitoring will
   * re-import on next scan, which is the operator's "find a replacement"
   * path. */
  unmonitor?: boolean;
};

/**
 * DELETE /api/admin/tracks/{id} — admin-only. Deletes the file from
 * disk and the DB row, cascading album/artist tidy-up. Optionally
 * unmonitors the track in Lidarr.
 *
 * On success returns the deleted track id plus optional album/artist
 * ids when their parent row was tidied up by the server-side cascade.
 * Caller is responsible for invalidating any TanStack Query keys the
 * deleted entities backed.
 */
export async function removeTrack(
  id: string,
  options: RemoveTrackOptions = {}
): Promise<RemoveTrackResult> {
  const params = new URLSearchParams();
  if (options.unmonitor) params.set('unmonitor', 'true');
  const qs = params.toString();
  const url = `/api/admin/tracks/${encodeURIComponent(id)}${qs ? '?' + qs : ''}`;
  return (await apiFetch(url, { method: 'DELETE' })) as RemoveTrackResult;
}
