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 { getScatter, useScatter } from './scatter'
import type { ScatterWidgetProps } from './types'

describe('getScatter ↔ useScatter parity', () => {
  beforeEach(() => {
    useSourceStore.setState({ sources: {}, filters: {} })
  })

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

    const expected = [
      [1, 2],
      [3, 4],
    ]
    const widgetSpy = vi.fn().mockResolvedValue(expected)

    const widgetProps: ScatterWidgetProps = {
      xAxisColumn: 'income',
      yAxisColumn: 'spending',
      xAxisJoinOperation: 'count',
      yAxisJoinOperation: 'count',
    } as unknown as ScatterWidgetProps

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

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

    expect(widgetSpy).toHaveBeenCalledOnce()

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

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

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

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