import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createApiKey } from "../../lib/adminApi";
import ApiKeyCreatePage from "./ApiKeyCreatePage";

vi.mock("../../lib/adminApi", () => ({
  createApiKey: vi.fn(async () => ({
    apiKey: {
      id: "api-key-id",
      name: "org-context-client",
      client_id: "client-id",
      scopes: ["audit:read", "user:read", "org-context:read"],
      status: "active",
      createdAt: "2026-05-13T00:00:00Z",
    },
    clientSecret: "secret",
  })),
}));

function renderPage() {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: { retry: false },
      mutations: { retry: false },
    },
  });

  return render(
    <QueryClientProvider client={queryClient}>
      <MemoryRouter>
        <ApiKeyCreatePage />
      </MemoryRouter>
    </QueryClientProvider>,
  );
}

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

  it("renders org-context:read as a selectable API key scope", () => {
    renderPage();

    expect(screen.getByText("조직 Context 조회")).toBeInTheDocument();
    expect(screen.getByText("ID: org-context:read")).toBeInTheDocument();
  });

  it("includes org-context:read in the create request when selected", async () => {
    const user = userEvent.setup();
    renderPage();

    await user.type(
      screen.getByLabelText("서비스 또는 목적 식별 이름"),
      "org-context-client",
    );
    await user.click(screen.getByRole("button", { name: /조직 Context 조회/ }));
    await user.click(screen.getByRole("button", { name: /API 키 발급하기/ }));

    await waitFor(() => {
      expect(createApiKey).toHaveBeenCalledWith(
        expect.objectContaining({
          name: "org-context-client",
          scopes: expect.arrayContaining(["org-context:read"]),
        }),
      );
    });
  });
});
