import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { UsersTab } from "../UsersTab";
import type { ServiceInstance } from "../../../types";

const instance: ServiceInstance = {
	id: "auth-1",
	service_type: "authentik",
	name: "Main Authentik",
	config: { base_url: "https://auth.example.com", timeout_seconds: 10 },
	secrets_set: { api_token: true },
	enabled: true,
	created_at: 1_700_000_000,
	updated_at: 1_700_000_000,
};

vi.mock("../../../hooks/useAuthentik", () => ({
	useAuthentikAccessSummary: vi.fn(() => ({
		data: {
			items: [
				{
					id: "1",
					username: "alice",
					name: "Alice",
					email: "alice@example.com",
					is_active: true,
					is_superuser: true,
					is_staff: false,
					groups: [{ id: "admins", name: "Admins", known: true }],
				},
				{
					id: "2",
					username: "bob",
					name: "Bob",
					email: "bob@example.com",
					is_active: false,
					is_superuser: false,
					is_staff: true,
					groups: [{ id: "gone", name: "Unknown group (gone)", known: false }],
				},
			],
			total: 2,
			page: 1,
			page_size: 25,
		},
		isLoading: false,
	})),
}));

describe("UsersTab", () => {
	it("renders group membership and explicit privilege metadata", () => {
		render(<UsersTab instance={instance} />);
		expect(screen.getByText("Alice")).toBeInTheDocument();
		expect(screen.getByText("bob")).toBeInTheDocument();
		expect(screen.getByText("Admins")).toBeInTheDocument();
		expect(screen.getByText("Unknown group (gone)")).toBeInTheDocument();
		expect(screen.getByText("Superuser")).toBeInTheDocument();
		expect(screen.getByText("Staff")).toBeInTheDocument();
		expect(
			screen.getByText(/not a complete effective-authorization calculation/i),
		).toBeInTheDocument();
	});

	it("renders search input and pagination", () => {
		render(<UsersTab instance={instance} />);
		expect(screen.getByPlaceholderText("Search users…")).toBeInTheDocument();
		expect(screen.getByText(/2 users/)).toBeInTheDocument();
		expect(screen.getByText("Previous")).toBeInTheDocument();
		expect(screen.getByText("Next")).toBeInTheDocument();
	});
});
