import { describe, it, expect, beforeEach, vi } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useSourceStore } from '../providers/sources/store'
import type { QuerySource, Source } from '../providers/sources/types'
import { getCategories, useCategories } from './categories'

/**
 * End-to-end parity check: a value warmed by calling
 * `queryClient.prefetchQuery(getCategories(...))` is read by `useCategories`
 * on the first render with no fetching, proving the imperative path and the
 * reactive hook share an identical cache key.
 */
describe('getCategories ↔ useCategories parity', () => {
  beforeEach(() => {
    useSourceStore.setState({ sources: {}, filters: {} })
  })

  it('useCategories returns prefetched data on first render without re-fetching', async () => {
    const queryClient = new QueryClient({
      defaultOptions: { queries: { retry: false, staleTime: Infinity } },
    })

    const expected = [{ name: 'A', value: 1 }]
    const widgetSpy = vi.fn().mockResolvedValue(expected)

    const sourceConfig: Omit<Source<QuerySource>, 'id'> = {
      type: 'query',
      data: 'SELECT 1',
      connectionName: 'conn',
      apiBaseUrl: 'http://api',
    }
    useSourceStore.getState().setSource<QuerySource>('demo', sourceConfig)

    const source = useSourceStore.getState().sources.demo
    if (source?.widgets) {
      source.widgets.getCategories = widgetSpy
    }

    await queryClient.prefetchQuery(
      getCategories({
        accessToken: 'tok',
        sourceId: 'demo',
        widgetProps: { column: 'CATEGORY', operation: 'count' },
      }),
    )

    expect(widgetSpy).toHaveBeenCalledOnce()

    const wrapper = ({ children }: { children: React.ReactNode }) => (
      <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
    )

    const { result } = renderHook(
      () =>
        useCategories({
          accessToken: 'tok',
          sourceId: 'demo',
          widgetProps: { column: 'CATEGORY', operation: 'count' },
        }),
      { wrapper },
    )

    await waitFor(() => {
      expect(result.current.data).toEqual(expected)
    })

    // `useCategories` should NOT have triggered an additional fetch (cache hit)
    expect(widgetSpy).toHaveBeenCalledOnce()
  })
})
