import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react';
import { useEnvironmentStore } from '../environment-store';

vi.mock('../client', () => ({
  api: { GET: vi.fn(), POST: vi.fn() },
}));

import { api as apiClient } from '../client';
import { useAlerts, useUnreadCount } from './alerts';

function wrapper({ children }: { children: ReactNode }) {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
}

describe('useAlerts', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    useEnvironmentStore.setState({ environment: 'dev' });
  });

  it('fetches alerts for selected env and passes filter query params', async () => {
    (apiClient.GET as any).mockResolvedValue({ data: [], error: null });
    const { result } = renderHook(
      () => useAlerts({ state: 'FIRING', severity: ['CRITICAL', 'WARNING'] }),
      { wrapper },
    );
    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(apiClient.GET).toHaveBeenCalledWith(
      '/environments/{envSlug}/alerts',
      expect.objectContaining({
        params: expect.objectContaining({
          path: { envSlug: 'dev' },
          query: expect.objectContaining({
            state: ['FIRING'],
            severity: ['CRITICAL', 'WARNING'],
            limit: 100,
          }),
        }),
      }),
    );
  });

  it('does not fetch when no env is selected', () => {
    useEnvironmentStore.setState({ environment: undefined });
    const { result } = renderHook(() => useAlerts(), { wrapper });
    expect(result.current.fetchStatus).toBe('idle');
    expect(apiClient.GET).not.toHaveBeenCalled();
  });
});

describe('useUnreadCount', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    useEnvironmentStore.setState({ environment: 'dev' });
  });

  it('returns the server payload unmodified', async () => {
    (apiClient.GET as any).mockResolvedValue({
      data: { total: 3, bySeverity: { CRITICAL: 1, WARNING: 2, INFO: 0 } },
      error: null,
    });
    const { result } = renderHook(() => useUnreadCount(), { wrapper });
    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(result.current.data).toEqual({
      total: 3,
      bySeverity: { CRITICAL: 1, WARNING: 2, INFO: 0 },
    });
  });
});
