import { useQuery } from '@tanstack/react-query';

import { fetchContactLogs } from '@/services/contactLogService';
import { fetchMaterials } from '@/services/materialService';
import { fetchMerchantContacts } from '@/services/merchantService';
import { fetchInquiryBatchOptions, fetchInquiryTasks } from '@/services/inquiryService';
import { fetchInquiryStatuses } from '@/services/automationService';
import {
  fetchSearchResults,
  fetchSearchStageSummaries,
} from '@/services/searchService';
import {
  fetchStandardizationFailures,
  fetchStandardizationTasks,
  fetchStandardized,
} from '@/services/standardizedService';
import { queryKeys } from '@/lib/queryKeys';

export function useStandardizedResultsQuery() {
  return useQuery({
    queryKey: queryKeys.standardization.successes,
    queryFn: () => fetchStandardized(),
  });
}

export function useStandardizationFailuresQuery() {
  return useQuery({
    queryKey: queryKeys.standardization.failures,
    queryFn: () => fetchStandardizationFailures(),
  });
}

export function useStandardizationTasksQuery() {
  return useQuery({
    queryKey: queryKeys.standardization.tasks,
    queryFn: () => fetchStandardizationTasks(),
    refetchInterval: (query) => {
      const tasks = query.state.data ?? [];
      return tasks.some((task) => task.status === 'pending' || task.status === 'processing' || task.status === 'stopping')
        ? 2000
        : false;
    },
    refetchIntervalInBackground: true,
  });
}

export function useSearchResultsBundleQuery() {
  return useQuery({
    queryKey: queryKeys.search.resultsBundle,
    queryFn: async () => {
      const [searchResults, stageSummaries, merchantContacts, materials, standardized, contactLogs] = await Promise.all([
        fetchSearchResults({ includePlaceholders: true }),
        fetchSearchStageSummaries(),
        fetchMerchantContacts(),
        fetchMaterials(),
        fetchStandardized(),
        fetchContactLogs(),
      ]);

      return {
        searchResults,
        stageSummaries,
        merchantContacts,
        materials,
        standardized,
        contactLogs,
      };
    },
  });
}

export function useInquiryDashboardQuery() {
  return useQuery({
    queryKey: queryKeys.inquiry.dashboard,
    queryFn: async () => {
      const [tasks, batchOptions, progresses] = await Promise.all([
        fetchInquiryTasks(),
        fetchInquiryBatchOptions(),
        fetchInquiryStatuses(),
      ]);

      return {
        tasks,
        batchOptions,
        progresses,
      };
    },
    refetchInterval: 3000,
    refetchIntervalInBackground: true,
  });
}
