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

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

const mockedApiClient = vi.mocked(apiClient);

describe('useApplicationStatsQuery', () => {
  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 application stats successfully', async () => {
    const mockStats = {
      flyerCount: 150,
      userCount: 500,
      flyerItemCount: 5000,
      storeCount: 25,
      pendingCorrectionsCount: 10,
      recipeCount: 75,
    };
    // API returns wrapped response: { success: true, data: {...} }
    mockedApiClient.getApplicationStats.mockResolvedValue({
      ok: true,
      json: () => Promise.resolve({ success: true, data: mockStats }),
    } as Response);

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

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

    expect(mockedApiClient.getApplicationStats).toHaveBeenCalled();
    expect(result.current.data).toEqual(mockStats);
  });

  it('should handle API error with error message', async () => {
    mockedApiClient.getApplicationStats.mockResolvedValue({
      ok: false,
      status: 403,
      json: () => Promise.resolve({ message: 'Admin access required' }),
    } as Response);

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

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

    expect(result.current.error?.message).toBe('Admin access required');
  });

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

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

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

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

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