import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { adminApi } from "../lib/api";
import { ActionCenterPage } from "./ActionCenterPage";

vi.mock("../lib/api", () => ({
  adminApi: {
    get: vi.fn(),
    post: vi.fn(),
  },
}));

describe("ActionCenterPage", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("loads actions and runs a guarded workflow", async () => {
    vi.mocked(adminApi.get).mockResolvedValue({
      data: {
        actions: [
          {
            description: "Disable a user's access to a tablo.",
            fields: [
              { id: "tabloId", label: "Tablo ID", required: true },
              { id: "userId", label: "User ID", required: true },
              { id: "reason", label: "Reason", required: true },
            ],
            id: "deactivate_tablo_access",
            label: "Deactivate Tablo Access",
          },
        ],
      },
    });
    vi.mocked(adminApi.post).mockResolvedValue({
      data: {
        message: "Tablo access deactivated and logged.",
        success: true,
      },
    });

    render(<ActionCenterPage />);

    expect(await screen.findByText(/action center/i)).toBeInTheDocument();

    fireEvent.change(screen.getByLabelText(/tablo id/i), {
      target: { value: "tablo-1" },
    });
    fireEvent.change(screen.getByLabelText(/user id/i), {
      target: { value: "user-1" },
    });
    fireEvent.change(screen.getByLabelText(/reason/i), {
      target: { value: "manual cleanup" },
    });
    fireEvent.click(screen.getByRole("button", { name: /run action/i }));

    await waitFor(() =>
      expect(adminApi.post).toHaveBeenCalledWith("/admin/actions/deactivate_tablo_access/run", {
        reason: "manual cleanup",
        tabloId: "tablo-1",
        userId: "user-1",
      })
    );
    expect(await screen.findByText(/deactivated and logged/i)).toBeInTheDocument();
  });
});
