import { afterEach, describe, expect, it, vi } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import { useServerStatus } from "../useServerStatus";
import { useBlocklistStatus } from "../useBlocklistStatus";
import * as dashboardApi from "../../api/dashboard";
import * as blocklistApi from "../../api/blocklist";

vi.mock("../../api/dashboard");
vi.mock("../../api/blocklist");

describe("useServerStatus", () => {
  const fetchMock = vi.mocked(dashboardApi.fetchServerStatus);

  afterEach(() => {
    fetchMock.mockReset();
  });

  it("fetches server status with an AbortSignal", async () => {
    fetchMock.mockResolvedValue({
      status: {
        online: true,
        version: "1.0.0",
        active_jails: 2,
        total_bans: 5,
        total_failures: 1,
      },
    });

    const { result, unmount } = renderHook(() => useServerStatus());

    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });

    expect(fetchMock).toHaveBeenCalledWith(expect.any(AbortSignal));
    expect(result.current.status).toEqual({
      online: true,
      version: "1.0.0",
      active_jails: 2,
      total_bans: 5,
      total_failures: 1,
    });

    unmount();
  });
});

describe("useBlocklistStatus", () => {
  const fetchMock = vi.mocked(blocklistApi.fetchSchedule);

  afterEach(() => {
    fetchMock.mockReset();
  });

  it("polls schedule state with an AbortSignal", async () => {
    fetchMock.mockResolvedValue({
      config: {
        frequency: "daily",
        interval_hours: 24,
        hour: 1,
        minute: 0,
        day_of_week: 0,
      },
      next_run_at: null,
      last_run_at: null,
      last_run_errors: true,
    });

    const { result, unmount } = renderHook(() => useBlocklistStatus());

    await waitFor(() => {
      expect(fetchMock).toHaveBeenCalledWith(expect.any(AbortSignal));
    });

    expect(result.current.hasErrors).toBe(true);
    unmount();
  });
});
