// src/hooks/queries/useCategoriesQuery.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 { useCategoriesQuery } from './useCategoriesQuery';
import * as apiClient from '../../services/apiClient';

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

const mockedApiClient = vi.mocked(apiClient);

describe('useCategoriesQuery', () => {
  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 categories successfully', async () => {
    const mockCategories = [
      { category_id: 1, name: 'Dairy' },
      { category_id: 2, name: 'Bakery' },
      { category_id: 3, name: 'Produce' },
    ];
    // API returns wrapped response: { success: true, data: [...] }
    mockedApiClient.fetchCategories.mockResolvedValue({
      ok: true,
      json: () => Promise.resolve({ success: true, data: mockCategories }),
    } as Response);

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

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

    expect(mockedApiClient.fetchCategories).toHaveBeenCalled();
    expect(result.current.data).toEqual(mockCategories);
  });

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

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

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

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

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

    const { result } = renderHook(() => useCategoriesQuery(), { 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.fetchCategories.mockResolvedValue({
      ok: false,
      status: 500,
      json: () => Promise.resolve({ message: '' }),
    } as Response);

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

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

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

  it('should return empty array for no categories', async () => {
    // API returns wrapped response: { success: true, data: [] }
    mockedApiClient.fetchCategories.mockResolvedValue({
      ok: true,
      json: () => Promise.resolve({ success: true, data: [] }),
    } as Response);

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

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

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