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(), PUT: vi.fn(), DELETE: vi.fn() },
}));

import { api as apiClient } from '../client';
import { useAlertRules, useSetAlertRuleEnabled } from './alertRules';

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

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

  it('fetches rules for selected env', async () => {
    (apiClient.GET as any).mockResolvedValue({ data: [], error: null });
    const { result } = renderHook(() => useAlertRules(), { wrapper });
    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(apiClient.GET).toHaveBeenCalledWith(
      '/environments/{envSlug}/alerts/rules',
      { params: { path: { envSlug: 'prod' } } },
    );
  });
});

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

  it('POSTs to /enable when enabling', async () => {
    (apiClient.POST as any).mockResolvedValue({ error: null });
    const { result } = renderHook(() => useSetAlertRuleEnabled(), { wrapper });
    await result.current.mutateAsync({ id: 'r1', enabled: true });
    expect(apiClient.POST).toHaveBeenCalledWith(
      '/environments/{envSlug}/alerts/rules/{id}/enable',
      { params: { path: { envSlug: 'prod', id: 'r1' } } },
    );
  });

  it('POSTs to /disable when disabling', async () => {
    (apiClient.POST as any).mockResolvedValue({ error: null });
    const { result } = renderHook(() => useSetAlertRuleEnabled(), { wrapper });
    await result.current.mutateAsync({ id: 'r1', enabled: false });
    expect(apiClient.POST).toHaveBeenCalledWith(
      '/environments/{envSlug}/alerts/rules/{id}/disable',
      { params: { path: { envSlug: 'prod', id: 'r1' } } },
    );
  });
});
