import { createQuery } from '@tanstack/svelte-query';
import { api, apiFetch } from './client';
import { qk } from './queries';
import type {
  LidarrQuarantineRow,
  LidarrQuarantineMineRow,
  LidarrQuarantineReason
} from './types';

export type FlagParams = {
  track_id: string;
  reason: LidarrQuarantineReason;
  notes?: string;
};

export async function flagTrack(params: FlagParams): Promise<LidarrQuarantineRow> {
  const body: FlagParams = { track_id: params.track_id, reason: params.reason };
  if (params.notes && params.notes.length > 0) body.notes = params.notes;
  return api.post<LidarrQuarantineRow>('/api/quarantine', body);
}

// Server returns 204 (no body) for DELETE; apiFetch handles it.
export async function unflagTrack(trackID: string): Promise<void> {
  await apiFetch(`/api/quarantine/${trackID}`, { method: 'DELETE' });
}

export async function listMyQuarantine(): Promise<LidarrQuarantineMineRow[]> {
  return api.get<LidarrQuarantineMineRow[]>('/api/quarantine/mine');
}

export function createMyQuarantineQuery() {
  return createQuery({
    queryKey: qk.myQuarantine(),
    queryFn: listMyQuarantine,
    staleTime: 60_000
  });
}
