import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import BackupDashboardWidget from "../BackupDashboardWidget";
import { useBackupDashboard } from "../../hooks/useBackups";

// The widget reads from the react-query hook; mocking `useBackupDashboard` lets
// us exercise the render paths without a QueryClientProvider or network.
vi.mock("../../hooks/useBackups", () => ({
	useBackupDashboard: vi.fn(),
}));

const mockUseBackupDashboard = vi.mocked(useBackupDashboard);
type DashboardResult = ReturnType<typeof useBackupDashboard>;

function mockResult(
	data: DashboardResult["data"],
	isLoading = false,
): DashboardResult {
	return { data, isLoading } as DashboardResult;
}

beforeEach(() => {
	mockUseBackupDashboard.mockReset();
});

describe("BackupDashboardWidget", () => {
	it("renders the loading state while data is pending", () => {
		mockUseBackupDashboard.mockReturnValue(mockResult(undefined, true));
		render(<BackupDashboardWidget />);
		expect(screen.getByText("Loading…")).toBeInTheDocument();
	});

	it("renders the backup dashboard stats (jobs / 24h success)", () => {
		mockUseBackupDashboard.mockReturnValue(
			mockResult({
				total_jobs: 4,
				success_rate_24h: 96,
				active_alerts: 0,
				last_failed_at: null,
			}),
		);
		render(<BackupDashboardWidget />);
		expect(screen.getByText("4")).toBeInTheDocument();
		expect(screen.getByText("96%")).toBeInTheDocument();
		expect(screen.getByText("Jobs")).toBeInTheDocument();
		expect(screen.getByText("24h Success")).toBeInTheDocument();
	});

	it("renders a destructive Badge for active alerts and shows last-failed time", () => {
		mockUseBackupDashboard.mockReturnValue(
			mockResult({
				total_jobs: 2,
				success_rate_24h: 50,
				active_alerts: 3,
				last_failed_at: 1_700_000_000,
			}),
		);
		render(<BackupDashboardWidget />);
		const badge = screen.getByText("3");
		expect(badge.getAttribute("data-variant")).toBe("destructive");
		expect(screen.getByText(/Last failed:/)).toBeInTheDocument();
	});
});
