import type { DataTag } from '@tanstack/react-query';
import {
  queryOptions,
  useQuery,
  useSuspenseQuery,
} from '@tanstack/react-query';
import type { Channel } from '@tunarr/types';
import type { ApiClient } from '../external/api';
import { useTunarrApi } from './useTunarrApi';

export const channelsQuery = (
  apiClient: ApiClient,
  initialData: Channel[] = [],
) =>
  queryOptions({
    queryKey: ['channels'] as DataTag<['channels'], Channel[]>,
    queryFn: () => apiClient.get('/api/channels'),
    initialData,
  });

export const useChannels = (initialData: Channel[] = []) => {
  const apiClient = useTunarrApi();
  return useQuery(channelsQuery(apiClient, initialData));
};

export const useChannelsSuspense = (
  params?: Partial<ReturnType<typeof channelsQuery>>,
) => {
  const apiClient = useTunarrApi();
  return useSuspenseQuery({ ...channelsQuery(apiClient), ...(params ?? {}) });
};

export const channelQuery = (
  apiClient: ApiClient,
  id: string,
  enabled: boolean = true,
) =>
  queryOptions({
    queryKey: ['channels', id] as DataTag<['channels', string], Channel>,
    queryFn: async () =>
      apiClient.get('/api/channels/:id', {
        params: { id },
      }),
    enabled: id.length > 0 && enabled,
    staleTime: 10_000,
  });

export const useChannel = (
  id: string,
  enabled: boolean = true,
  initialData: Channel | undefined = undefined,
) => {
  const apiClient = useTunarrApi();
  return useQuery({ ...channelQuery(apiClient, id, enabled), initialData });
};

export const useChannelSuspense = (id: string, enabled: boolean = true) => {
  const apiClient = useTunarrApi();
  return useSuspenseQuery(channelQuery(apiClient, id, enabled));
};

// If we absolutely have initialData defined, we can use this hook instead,
// to eliminate the typing possiblity of "| undefined" for the resulting Channel
export const useChannelWithInitialData = (
  id: string,
  initialData: Channel,
  enabled: boolean = true,
) => {
  const apiClient = useTunarrApi();
  return useQuery({ ...channelQuery(apiClient, id, enabled), initialData });
};
