// src/hooks/queries/useShoppingListsQuery.test.tsx
import { renderHook, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react';
import { useShoppingListsQuery } from './useShoppingListsQuery';
import * as apiClient from '../../services/apiClient';

vi.mock('../../services/apiClient');

const mockedApiClient = vi.mocked(apiClient);

describe('useShoppingListsQuery', () => {
  let queryClient: QueryClient;

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

  beforeEach(() => {
    vi.resetAllMocks();
    queryClient = new QueryClient({
      defaultOptions: {
        queries: { retry: false },
      },
    });
  });

  it('should fetch shopping lists when enabled', async () => {
    const mockShoppingLists = [
      { shopping_list_id: 1, name: 'Weekly Groceries', items: [] },
      { shopping_list_id: 2, name: 'Party Supplies', items: [] },
    ];
    mockedApiClient.fetchShoppingLists.mockResolvedValue({
      ok: true,
      json: () => Promise.resolve(mockShoppingLists),
    } as Response);

    const { result } = renderHook(() => useShoppingListsQuery(true), { wrapper });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));

    expect(mockedApiClient.fetchShoppingLists).toHaveBeenCalled();
    expect(result.current.data).toEqual(mockShoppingLists);
  });

  it('should not fetch shopping lists when disabled', async () => {
    const { result } = renderHook(() => useShoppingListsQuery(false), { wrapper });

    // Wait a bit to ensure the query doesn't run
    await new Promise((resolve) => setTimeout(resolve, 100));

    expect(mockedApiClient.fetchShoppingLists).not.toHaveBeenCalled();
    expect(result.current.isLoading).toBe(false);
    expect(result.current.isFetching).toBe(false);
  });

  it('should handle API error with error message', async () => {
    mockedApiClient.fetchShoppingLists.mockResolvedValue({
      ok: false,
      status: 401,
      json: () => Promise.resolve({ message: 'Unauthorized' }),
    } as Response);

    const { result } = renderHook(() => useShoppingListsQuery(true), { wrapper });

    await waitFor(() => expect(result.current.isError).toBe(true));

    expect(result.current.error?.message).toBe('Unauthorized');
  });

  it('should handle API error without message', async () => {
    mockedApiClient.fetchShoppingLists.mockResolvedValue({
      ok: false,
      status: 500,
      json: () => Promise.reject(new Error('Parse error')),
    } as Response);

    const { result } = renderHook(() => useShoppingListsQuery(true), { wrapper });

    await waitFor(() => expect(result.current.isError).toBe(true));

    expect(result.current.error?.message).toBe('Request failed with status 500');
  });

  it('should use fallback message when error.message is empty', async () => {
    mockedApiClient.fetchShoppingLists.mockResolvedValue({
      ok: false,
      status: 500,
      json: () => Promise.resolve({ message: '' }),
    } as Response);

    const { result } = renderHook(() => useShoppingListsQuery(true), { wrapper });

    await waitFor(() => expect(result.current.isError).toBe(true));

    expect(result.current.error?.message).toBe('Failed to fetch shopping lists');
  });

  it('should return empty array for no shopping lists', async () => {
    mockedApiClient.fetchShoppingLists.mockResolvedValue({
      ok: true,
      json: () => Promise.resolve([]),
    } as Response);

    const { result } = renderHook(() => useShoppingListsQuery(true), { wrapper });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));

    expect(result.current.data).toEqual([]);
  });
});
