import { createQuery, createMutation } from '@tanstack/svelte-query';
import type { QueryClient } from '@tanstack/svelte-query';
import { api } from './client';

export type LBStatus = {
  enabled: boolean;
  token_set: boolean;
  last_scrobbled_at: string | null;
};

export function getListenBrainzStatus(): Promise<LBStatus> {
  return api.get<LBStatus>('/api/me/listenbrainz');
}

export function setListenBrainzToken(token: string): Promise<LBStatus> {
  return api.put<LBStatus>('/api/me/listenbrainz', { token });
}

export function setListenBrainzEnabled(enabled: boolean): Promise<LBStatus> {
  return api.put<LBStatus>('/api/me/listenbrainz', { enabled });
}

export const LB_QUERY_KEY = ['settings', 'listenbrainz'] as const;

export function createLBStatusQuery() {
  return createQuery({
    queryKey: LB_QUERY_KEY,
    queryFn: getListenBrainzStatus
  });
}

export function createTokenMutation(queryClient: QueryClient) {
  return createMutation<LBStatus, Error, string>({
    mutationFn: (token: string) => setListenBrainzToken(token),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: LB_QUERY_KEY })
  });
}

export function createEnabledMutation(queryClient: QueryClient) {
  return createMutation<LBStatus, Error, boolean>({
    mutationFn: (enabled: boolean) => setListenBrainzEnabled(enabled),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: LB_QUERY_KEY })
  });
}
