import { QueryClient } from '@tanstack/react-query';
import { describe, expect, it, vi } from 'vitest';

import {
  getNavigationRefreshQueryKeys,
  refreshNavigationQueries,
} from '@/lib/navigationRefresh';
import { queryKeys } from '@/lib/queryKeys';

describe('navigationRefresh', () => {
  it('maps standardization success route to success rows and batch options', () => {
    expect(getNavigationRefreshQueryKeys({ pathname: '/standardized' })).toEqual([
      queryKeys.standardization.successes,
      queryKeys.procurement.batchOptions,
    ]);
  });

  it('maps standardization failure route to failure rows and tasks', () => {
    expect(getNavigationRefreshQueryKeys({ pathname: '/standardized', search: '?tab=failed' })).toEqual([
      queryKeys.standardization.failures,
      queryKeys.standardization.tasks,
    ]);
  });

  it('maps standardization task route to task views', () => {
    expect(getNavigationRefreshQueryKeys({ pathname: '/standardized', search: '?tab=tasks' })).toEqual([
      queryKeys.standardization.tasks,
      queryKeys.standardization.monitorTasks,
    ]);
  });

  it('invalidates and actively refetches target queries once per menu click', () => {
    const queryClient = new QueryClient();
    const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue();
    const refetchSpy = vi.spyOn(queryClient, 'refetchQueries').mockResolvedValue();

    refreshNavigationQueries(queryClient, { pathname: '/standardized', search: '?tab=failed' });

    expect(invalidateSpy).toHaveBeenCalledTimes(2);
    expect(refetchSpy).toHaveBeenCalledTimes(2);
    expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: queryKeys.standardization.failures });
    expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: queryKeys.standardization.tasks });
    expect(refetchSpy).toHaveBeenCalledWith({ queryKey: queryKeys.standardization.failures, type: 'active' });
    expect(refetchSpy).toHaveBeenCalledWith({ queryKey: queryKeys.standardization.tasks, type: 'active' });
  });
});
