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

// Search-only. Admin-side Lidarr config + connection probing lives in admin.ts.

// searchLidarr proxies the user-facing Lidarr search endpoint. URLSearchParams
// handles encoding (spaces, quotes, ampersands) so callers can pass q raw.
export async function searchLidarr(
  q: string,
  kind: LidarrRequestKind
): Promise<LidarrSearchResult[]> {
  const params = new URLSearchParams({ q, kind });
  return api.get<LidarrSearchResult[]>(`/api/lidarr/search?${params.toString()}`);
}

// staleTime mirrors the spec §11 60s server-side LRU cache: re-issuing the
// same query within a minute hits cache on the server, so there's no point
// in marking it stale client-side any sooner.
export function createLidarrSearchQuery(q: string, kind: LidarrRequestKind) {
  return createQuery({
    queryKey: qk.lidarrSearch(q, kind),
    queryFn: () => searchLidarr(q, kind),
    enabled: q.length > 0,
    staleTime: 60_000
  });
}
