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

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

const mockedApiClient = vi.mocked(apiClient);

describe('useMasterItemsQuery', () => {
  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 master items successfully', async () => {
    const mockMasterItems = [
      { master_item_id: 1, name: 'Milk', category: 'Dairy' },
      { master_item_id: 2, name: 'Bread', category: 'Bakery' },
      { master_item_id: 3, name: 'Eggs', category: 'Dairy' },
    ];
    mockedApiClient.fetchMasterItems.mockResolvedValue({
      ok: true,
      json: () => Promise.resolve(mockMasterItems),
    } as Response);

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

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

    expect(mockedApiClient.fetchMasterItems).toHaveBeenCalled();
    expect(result.current.data).toEqual(mockMasterItems);
  });

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

    const { result } = renderHook(() => useMasterItemsQuery(), { 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.fetchMasterItems.mockResolvedValue({
      ok: false,
      status: 500,
      json: () => Promise.reject(new Error('Parse error')),
    } as Response);

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

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

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

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

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

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

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

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