import { createQuery } from '@tanstack/svelte-query';
import { api } from './client';
import { qk } from './queries';
import type { ArtistSuggestion, SuggestionSnooze } from './types';

export async function listSuggestions(limit = 12): Promise<ArtistSuggestion[]> {
  return api.get<ArtistSuggestion[]>(`/api/discover/suggestions?limit=${limit}`);
}

export function createSuggestionsQuery(limit = 12) {
  return createQuery({
    queryKey: qk.suggestions(limit),
    queryFn: () => listSuggestions(limit),
    staleTime: 5 * 60_000   // 5 minutes — see M5c spec §5
  });
}

// Parks a suggestion for the server's default period (90 days). `name` is
// REQUIRED by the server and is not optional bookkeeping: candidates are
// out-of-library, so there is no artists row to resolve a display name from
// and the snooze list would have nothing to render. Omitting it is a 400.
//
// No `days` is sent. There is deliberately no duration UI yet — that knob is
// slice 6 (#2377) — and hardcoding a value here would pin the default to the
// client instead of the server that owns it.
export async function snoozeSuggestion(mbid: string, name: string): Promise<void> {
  await api.post<null>(`/api/discover/suggestions/${encodeURIComponent(mbid)}/snooze`, { name });
}

// Brings a parked suggestion back immediately. The server 404s an MBID that
// was never snoozed; callers treat that as already-unsnoozed rather than as a
// failure, since the end state the user asked for is the one they get.
export async function unsnoozeSuggestion(mbid: string): Promise<void> {
  await api.del(`/api/discover/suggestions/${encodeURIComponent(mbid)}/snooze`);
}

export async function listSnoozes(): Promise<SuggestionSnooze[]> {
  return api.get<SuggestionSnooze[]>('/api/discover/snoozes');
}

export function createSnoozesQuery() {
  return createQuery({
    queryKey: qk.suggestionSnoozes(),
    queryFn: listSnoozes
    // No staleTime, unlike the suggestions query: this list is the only route
    // back to an un-snooze, so it must reflect a snooze made seconds ago
    // rather than a cached view of the world.
  });
}
