import { expect, test } from "@playwright/test";

test.describe("Tenant Schema Management", () => {
  test.beforeEach(async ({ page }) => {
    await page.addInitScript(() => {
      window.localStorage.setItem("locale", "ko");
      window.localStorage.setItem("admin_session", "fake-token");
      window.localStorage.setItem("RoleSwitcher-Collapsed", "true");
      (
        window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }
      )._IS_TEST_MODE = true;

      const authority = "http://localhost:5000/oidc";
      const client_id = "adminfront";
      const key = `oidc.user:${authority}:${client_id}`;
      const authData = {
        access_token: "fake-token",
        token_type: "Bearer",
        profile: { sub: "admin-user", name: "Admin", role: "super_admin" },
        expires_at: Math.floor(Date.now() / 1000) + 36000,
      };
      window.localStorage.setItem(key, JSON.stringify(authData));
    });

    await page.route("**/oidc/**", async (route) => {
      await route.fulfill({ json: { issuer: "http://localhost:5000/oidc" } });
    });
  });

  test("should force indexed when schema field is used as login ID", async ({
    page,
  }) => {
    let savedConfig: Record<string, unknown> | undefined;

    await page.route("**/api/v1/**", async (route) => {
      const url = route.request().url();
      const method = route.request().method();
      const headers = { "Access-Control-Allow-Origin": "*" };

      if (url.includes("/user/me")) {
        return route.fulfill({
          json: {
            id: "admin-user",
            name: "Admin",
            role: "super_admin",
            manageableTenants: [],
          },
          headers,
        });
      }

      if (url.includes("/admin/tenants/t-1") && method === "GET") {
        return route.fulfill({
          json: {
            id: "t-1",
            name: "Test Tenant",
            slug: "test-tenant",
            type: "COMPANY",
            status: "active",
            config: { userSchema: [] },
          },
          headers,
        });
      }

      if (url.includes("/admin/tenants/t-1") && method === "PUT") {
        const payload = route.request().postDataJSON() as {
          config?: Record<string, unknown>;
        };
        savedConfig = payload.config;
        return route.fulfill({
          json: {
            id: "t-1",
            name: "Test Tenant",
            slug: "test-tenant",
            type: "COMPANY",
            status: "active",
            config: savedConfig,
          },
          headers,
        });
      }

      return route.fulfill({ json: { items: [], total: 0 }, headers });
    });

    await page.goto("/tenants/t-1/schema");
    await expect(
      page.getByText(/사용자 스키마 확장|User Schema Extension/),
    ).toBeVisible();

    await page.getByRole("button", { name: /필드 추가/ }).click();
    await page
      .getByPlaceholder(/예: employee_id|e\.g\. employee_id/)
      .fill("emp_no");
    await page.getByPlaceholder("예: 사번").fill("사번");

    const indexedCheckbox = page.getByLabel(/검색 인덱스 필요|조회 인덱스/);
    await expect(indexedCheckbox).not.toBeChecked();
    await expect(indexedCheckbox).toBeEnabled();

    await page.getByLabel("로그인 ID로 사용").check();
    await expect(indexedCheckbox).toBeChecked();
    await expect(indexedCheckbox).toBeDisabled();

    await page
      .getByRole("button", { name: /변경사항 저장|스키마 저장|Save/ })
      .click();

    await expect
      .poll(() => savedConfig)
      .toMatchObject({
        userSchema: [
          {
            key: "emp_no",
            label: "사번",
            type: "text",
            indexed: true,
            isLoginId: true,
          },
        ],
      });
  });
});
