import { fireEvent, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, expect, it, vi } from "vitest";
import { AdminSecurityPanel } from "./AdminSecurityPanel";

const patchMutate = vi.fn();
const revealMutate = vi.fn();
const invalidateQueries = vi.fn();

vi.mock("@tanstack/react-query", async () => {
  const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
  return {
    ...actual,
    useQueryClient: () => ({ invalidateQueries }),
    useQuery: ({ queryKey }: { queryKey: string[] }) => {
      if (queryKey[0] === "admin-settings") {
        return {
          isLoading: false,
          data: { values: { enable_rate_limit: true, enable_docs: false, cookie_secure: false }, locks: {} }
        };
      }
      return {
        isLoading: false,
        data: {
          database: { user: "dbu", host: "dbh", port: 5432, database: "dbn" },
          connection_string_masked: "postgresql://***",
        }
      };
    },
    useMutation: (options?: { mutationFn?: unknown; onSuccess?: () => void }) => {
      if (options?.onSuccess) {
        return { mutate: patchMutate };
      }
      return { mutate: revealMutate, data: { key: "database_password", value: "secret" } };
    }
  };
});

vi.mock("../api/adminApi", () => ({
  getAdminSettings: vi.fn(),
  patchAdminSettings: vi.fn(),
  getInstallSecrets: vi.fn(),
  revealInstallSecret: vi.fn()
}));

describe("AdminSecurityPanel", () => {
  it("toggles settings and reveals secrets", () => {
    const client = new QueryClient();
    render(
      <QueryClientProvider client={client}>
        <AdminSecurityPanel />
      </QueryClientProvider>
    );

    fireEvent.click(screen.getAllByRole("switch")[1]);
    expect(patchMutate).toHaveBeenCalled();

    fireEvent.click(screen.getByRole("button", { name: "Reveal DB password" }));
    expect(revealMutate).toHaveBeenCalledWith("database_password");
    expect(screen.getByText(/database_password/i)).toBeInTheDocument();
  });
});
