import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen } from "@testing-library/react";
import type React from "react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createI18nMock } from "../../test/i18nMock";
import TenantCreatePage from "../tenants/routes/TenantCreatePage";
import { TenantProfilePage } from "../tenants/routes/TenantProfilePage";
import { TenantSchemaPage } from "../tenants/routes/TenantSchemaPage";

const tenants = [
  {
    id: "tenant-root",
    type: "COMPANY_GROUP",
    name: "한맥 가족",
    slug: "hanmac-family",
    description: "",
    status: "active",
    memberCount: 0,
    domains: ["hmac.kr"],
    config: { visibility: "public" },
    createdAt: "2026-05-01T00:00:00Z",
    updatedAt: "2026-05-01T00:00:00Z",
  },
  {
    id: "tenant-company",
    type: "COMPANY",
    parentId: "tenant-root",
    name: "GPDTDC",
    slug: "gpdtdc",
    description: "실 조직",
    status: "active",
    memberCount: 2,
    domains: ["gpdtdc.example.com"],
    config: {
      visibility: "public",
      userSchema: [
        {
          key: "employee_id",
          label: "사번",
          type: "text",
          required: false,
          adminOnly: false,
          isLoginId: true,
          indexed: true,
        },
      ],
    },
    createdAt: "2026-05-01T00:00:00Z",
    updatedAt: "2026-05-01T00:00:00Z",
  },
];

vi.mock("../../lib/i18n", () => createI18nMock());

vi.mock("../../lib/adminApi", () => ({
  fetchMe: vi.fn(async () => ({
    id: "admin-1",
    role: "super_admin",
  })),
  fetchAllTenants: vi.fn(async () => ({
    items: tenants,
    total: tenants.length,
  })),
  fetchTenant: vi.fn(async (id: string) => {
    return tenants.find((tenant) => tenant.id === id) ?? tenants[1];
  }),
  createTenant: vi.fn(async () => tenants[1]),
  updateTenant: vi.fn(async () => tenants[1]),
  deleteTenant: vi.fn(async () => undefined),
  approveTenant: vi.fn(async () => tenants[1]),
}));

function renderWithProviders(ui: React.ReactElement, entry: string) {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: { retry: false },
      mutations: { retry: false },
    },
  });

  return render(
    <QueryClientProvider client={queryClient}>
      <MemoryRouter initialEntries={[entry]}>{ui}</MemoryRouter>
    </QueryClientProvider>,
  );
}

describe("admin tenant detail page coverage smoke", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.spyOn(window, "confirm").mockReturnValue(true);
  });

  it("renders tenant create page with parent context", async () => {
    renderWithProviders(
      <Routes>
        <Route path="/tenants/new" element={<TenantCreatePage />} />
      </Routes>,
      "/tenants/new?parentId=tenant-root",
    );

    expect(await screen.findByText("테넌트 생성")).toBeInTheDocument();
    expect(screen.getByText("Tenant Profile")).toBeInTheDocument();
    expect(screen.getByText("정책 메모")).toBeInTheDocument();
  });

  it("renders tenant profile and schema management pages", async () => {
    renderWithProviders(
      <Routes>
        <Route
          path="/tenants/:tenantId"
          element={
            <>
              <TenantProfilePage />
              <TenantSchemaPage />
            </>
          }
        />
      </Routes>,
      "/tenants/tenant-company",
    );

    expect(await screen.findByDisplayValue("GPDTDC")).toBeInTheDocument();
    expect(screen.getByDisplayValue("gpdtdc")).toBeInTheDocument();
    expect(await screen.findByText("사용자 스키마 확장")).toBeInTheDocument();
    expect(screen.getByDisplayValue("employee_id")).toBeInTheDocument();
  });
});
