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 { getHistogram, useHistogram } from './histogram'
import type { HistogramWidgetProps } from './types'

/**
 * End-to-end parity check: a value warmed by calling
 * `queryClient.prefetchQuery(getHistogram(...))` is read by `useHistogram`
 * on the first render with no fetching.
 */
describe('getHistogram ↔ useHistogram parity', () => {
  beforeEach(() => {
    useSourceStore.setState({ sources: {}, filters: {} })
  })

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

    const expected = [10, 20, 30, 40]
    const widgetSpy = vi.fn().mockResolvedValue(expected)

    const widgetProps: HistogramWidgetProps = {
      column: 'revenue',
      ticks: [0, 1000, 5000, 10000],
    }

    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.getHistogram = widgetSpy
    }

    await queryClient.prefetchQuery(
      getHistogram({
        accessToken: 'tok',
        sourceId: 'demo',
        widgetProps,
      }),
    )

    expect(widgetSpy).toHaveBeenCalledOnce()

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

    const { result } = renderHook(
      () =>
        useHistogram({
          accessToken: 'tok',
          sourceId: 'demo',
          widgetProps,
        }),
      { wrapper },
    )

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

    expect(widgetSpy).toHaveBeenCalledOnce()
  })
})
