import type { QueryClient, QueryKey } from '@tanstack/react-query';

import { queryKeys } from '@/lib/queryKeys';

type NavigationTarget = {
  pathname: string;
  search?: string;
};

const materialsQueryKey = ['materials-supabase'] as const;
const materialsSourceFilesQueryKey = ['materials-source-files'] as const;
const sourceFilesQueryKey = ['source-files'] as const;

function getTab(search: string | undefined) {
  return new URLSearchParams(search ?? '').get('tab') ?? '';
}

function uniqueQueryKeys(queryKeysToRefresh: readonly QueryKey[]) {
  const seen = new Set<string>();
  return queryKeysToRefresh.filter((queryKey) => {
    const key = JSON.stringify(queryKey);
    if (seen.has(key)) {
      return false;
    }
    seen.add(key);
    return true;
  });
}

export function getNavigationRefreshQueryKeys(target: NavigationTarget): QueryKey[] {
  const tab = getTab(target.search);

  if (target.pathname === '/standardized') {
    if (tab === 'failed') {
      return [
        queryKeys.standardization.failures,
        queryKeys.standardization.tasks,
      ];
    }

    if (tab === 'tasks') {
      return [
        queryKeys.standardization.tasks,
        queryKeys.standardization.monitorTasks,
      ];
    }

    return [
      queryKeys.standardization.successes,
      queryKeys.procurement.batchOptions,
    ];
  }

  if (target.pathname === '/search-results') {
    return [
      queryKeys.search.resultsBundle,
      queryKeys.procurement.batchOptions,
    ];
  }

  if (target.pathname === '/smart-inquiry') {
    return [
      queryKeys.inquiry.dashboard,
      queryKeys.search.resultsBundle,
    ];
  }

  if (target.pathname === '/materials' || target.pathname === '/procurement-list-review') {
    return [
      materialsQueryKey,
      materialsSourceFilesQueryKey,
      queryKeys.procurement.batchOptions,
    ];
  }

  if (target.pathname === '/batches') {
    return [
      queryKeys.procurement.batchOptions,
      sourceFilesQueryKey,
      materialsQueryKey,
    ];
  }

  if (target.pathname === '/merchants') {
    return [
      queryKeys.search.resultsBundle,
    ];
  }

  if (target.pathname === '/contact-logs') {
    return [
      queryKeys.search.resultsBundle,
      queryKeys.inquiry.dashboard,
    ];
  }

  if (target.pathname === '/') {
    return [
      materialsQueryKey,
      queryKeys.standardization.successes,
      queryKeys.search.resultsBundle,
      queryKeys.inquiry.dashboard,
    ];
  }

  return [];
}

export function refreshNavigationQueries(queryClient: QueryClient, target: NavigationTarget) {
  uniqueQueryKeys(getNavigationRefreshQueryKeys(target)).forEach((queryKey) => {
    void queryClient.invalidateQueries({ queryKey });
    void queryClient.refetchQueries({ queryKey, type: 'active' });
  });
}
