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

test.describe("Bulk Actions and Tree Search", () => {
  test.beforeEach(async ({ page }) => {
    await page.addInitScript(() => {
      window.localStorage.setItem("locale", "ko");
      window.localStorage.setItem("admin_session", "fake-token");
      (
        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", role: "super_admin", name: "Admin" },
        expires_at: Math.floor(Date.now() / 1000) + 36000,
      };
      window.localStorage.setItem(key, JSON.stringify(authData));
    });

    // Capture ALL API calls to our mock host
    await page.route("**/api/v1/**", async (route) => {
      const url = route.request().url();
      const headers = { "Access-Control-Allow-Origin": "*" };

      if (url.includes("/user/me")) {
        return route.fulfill({
          json: {
            id: "admin",
            role: "super_admin",
            name: "Admin",
            manageableTenants: [],
          },
          headers,
        });
      }
      if (
        url.includes("/admin/users/bulk") &&
        route.request().method() === "PUT"
      ) {
        return route.fulfill({
          json: { results: [{ id: "u-1", success: true }] },
          headers,
        });
      }
      if (url.includes("/admin/users")) {
        return route.fulfill({
          json: {
            items: [
              {
                id: "u-1",
                name: "User One",
                email: "u1@test.com",
                status: "active",
                role: "user",
                createdAt: new Date().toISOString(),
              },
              {
                id: "u-2",
                name: "User Two",
                email: "u2@test.com",
                status: "active",
                role: "user",
                createdAt: new Date().toISOString(),
              },
            ],
            total: 2,
          },
          headers,
        });
      }
      if (url.includes("/organization")) {
        return route.fulfill({
          json: [
            { id: "g-1", name: "Engineering", slug: "eng", tenantId: "t-1" },
            { id: "g-2", name: "Sales", slug: "sales", tenantId: "t-1" },
          ],
          headers,
        });
      }
      if (url.includes("/admin/tenants/t-1")) {
        return route.fulfill({
          json: {
            id: "t-1",
            name: "Main Tenant",
            slug: "main",
            status: "active",
            type: "COMPANY",
          },
          headers,
        });
      }
      if (url.includes("/admin/tenants")) {
        return route.fulfill({
          json: {
            items: [
              { id: "t-1", name: "Main Tenant", slug: "main", type: "COMPANY" },
              {
                id: "g-1",
                name: "Engineering",
                slug: "eng",
                parentId: "t-1",
                type: "USER_GROUP",
              },
              {
                id: "g-2",
                name: "Sales",
                slug: "sales",
                parentId: "t-1",
                type: "USER_GROUP",
              },
            ],
            total: 3,
          },
          headers,
        });
      }

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

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

  test("should show bulk action bar when users are selected", async ({
    page,
  }) => {
    await page.goto("/users");
    // 로딩바 대기 대신 실제 데이터 텍스트 대기
    const table = page.locator("table");
    await expect(table).toContainText("User One", { timeout: 20000 });

    // 첫 번째 데이터의 체크박스 선택
    const userCheckbox = page.locator('table input[type="checkbox"]').nth(1);
    await userCheckbox.click();

    // 일괄 작업 바 확인
    const selectionBar = page.getByTestId("bulk-action-bar");
    await expect(selectionBar).toBeVisible({ timeout: 15000 });

    await expect(page.getByTestId("bulk-status-select")).toBeVisible({
      timeout: 10000,
    });
    await expect(page.getByTestId("bulk-apply-btn")).toBeVisible();

    // 전체 선택
    await page.locator('table input[type="checkbox"]').first().click();
    await expect(selectionBar).toBeVisible();

    // 선택 해제 버튼
    const closeBtn = page.getByTestId("bulk-close-btn");
    await closeBtn.click();

    await expect(selectionBar).not.toBeVisible({ timeout: 10000 });
  });

  test("should apply selected bulk status to selected users", async ({
    page,
  }) => {
    let capturedPayload: unknown = null;
    await page.route("**/api/v1/admin/users/bulk", async (route) => {
      if (route.request().method() === "PUT") {
        capturedPayload = route.request().postDataJSON();
        return route.fulfill({
          json: { results: [{ id: "u-1", success: true }] },
          headers: { "Access-Control-Allow-Origin": "*" },
        });
      }
      return route.fallback();
    });

    await page.goto("/users");
    await expect(page.locator("table")).toContainText("User One", {
      timeout: 20000,
    });

    await page.locator('table input[type="checkbox"]').nth(1).click();
    const selectionBar = page.getByTestId("bulk-action-bar");
    await expect(selectionBar).toBeVisible({ timeout: 15000 });

    await page.getByTestId("bulk-status-select").click();
    await page.getByRole("option", { name: /입사대기|Preboarding/i }).click();
    await page.getByTestId("bulk-apply-btn").click();

    await expect
      .poll(() => capturedPayload)
      .toEqual({
        userIds: ["u-1"],
        status: "preboarding",
      });
    await expect(selectionBar).not.toBeVisible({ timeout: 10000 });
  });

  test("should let super admins apply selected admin permission to selected users", async ({
    page,
  }) => {
    let capturedPayload: unknown = null;
    await page.route("**/api/v1/admin/users/bulk", async (route) => {
      if (route.request().method() === "PUT") {
        capturedPayload = route.request().postDataJSON();
        return route.fulfill({
          json: { results: [{ id: "u-1", success: true }] },
          headers: { "Access-Control-Allow-Origin": "*" },
        });
      }
      return route.fallback();
    });

    await page.goto("/users");
    await expect(page.locator("table")).toContainText("User One", {
      timeout: 20000,
    });

    await page.locator('table input[type="checkbox"]').nth(1).click();
    const selectionBar = page.getByTestId("bulk-action-bar");
    await expect(selectionBar).toBeVisible({ timeout: 15000 });

    await page.getByTestId("bulk-permission-select").click();
    await page
      .getByRole("option", { name: /시스템 관리자|Super Admin/i })
      .click();
    await page.getByTestId("bulk-apply-btn").click();

    await expect
      .poll(() => capturedPayload)
      .toEqual({
        userIds: ["u-1"],
        role: "super_admin",
      });
    await expect(selectionBar).not.toBeVisible({ timeout: 10000 });
  });

  test("should only expose super admin grant and revoke options in bulk permission select", async ({
    page,
  }) => {
    await page.goto("/users");
    await expect(page.locator("table")).toContainText("User One", {
      timeout: 20000,
    });

    await page.locator('table input[type="checkbox"]').nth(1).click();
    await expect(page.getByTestId("bulk-action-bar")).toBeVisible({
      timeout: 15000,
    });

    await page.getByTestId("bulk-permission-select").click();
    await expect(
      page.getByRole("option", { name: /시스템 관리자|Super Admin/i }),
    ).toBeVisible();
    await expect(
      page.getByRole("option", { name: /일반 사용자|User/i }),
    ).toBeVisible();
    await expect(
      page.getByRole("option", { name: /테넌트 관리자|Tenant Admin/i }),
    ).toHaveCount(0);
    await expect(
      page.getByRole("option", {
        name: /서비스 관리자|RP Admin|Service Admin/i,
      }),
    ).toHaveCount(0);
  });

  test("should let super admins revoke selected super admin permission", async ({
    page,
  }) => {
    let capturedPayload: unknown = null;
    await page.route("**/api/v1/admin/users/bulk", async (route) => {
      if (route.request().method() === "PUT") {
        capturedPayload = route.request().postDataJSON();
        return route.fulfill({
          json: { results: [{ id: "u-1", success: true }] },
          headers: { "Access-Control-Allow-Origin": "*" },
        });
      }
      return route.fallback();
    });

    await page.goto("/users");
    await expect(page.locator("table")).toContainText("User One", {
      timeout: 20000,
    });

    await page.locator('table input[type="checkbox"]').nth(1).click();
    await expect(page.getByTestId("bulk-action-bar")).toBeVisible({
      timeout: 15000,
    });

    await page.getByTestId("bulk-permission-select").click();
    await page.getByRole("option", { name: /일반 사용자|User/i }).click();
    await page.getByTestId("bulk-apply-btn").click();

    await expect
      .poll(() => capturedPayload)
      .toEqual({
        userIds: ["u-1"],
        role: "user",
      });
  });

  test("should not render role field on user detail page", async ({ page }) => {
    await page.unroute("**/api/v1/**");
    await page.route("**/api/v1/**", async (route) => {
      const url = route.request().url();
      const headers = { "Access-Control-Allow-Origin": "*" };

      if (url.includes("/user/me")) {
        return route.fulfill({
          json: {
            id: "admin",
            role: "super_admin",
            name: "Admin",
            manageableTenants: [],
          },
          headers,
        });
      }
      if (url.includes("/auth/password/policy")) {
        return route.fulfill({ json: { minLength: 12 }, headers });
      }
      if (url.includes("/admin/users/u-1/rp-history")) {
        return route.fulfill({ json: [], headers });
      }
      if (url.includes("/admin/users/u-1")) {
        return route.fulfill({
          json: {
            id: "u-1",
            name: "User One",
            email: "u1@test.com",
            phone: "",
            status: "active",
            role: "user",
            tenantSlug: "main",
            createdAt: new Date().toISOString(),
            metadata: {},
          },
          headers,
        });
      }
      if (url.includes("/admin/tenants")) {
        return route.fulfill({
          json: {
            items: [
              { id: "t-1", name: "Main Tenant", slug: "main", type: "COMPANY" },
            ],
            total: 1,
          },
          headers,
        });
      }

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

    await page.goto("/users/u-1");
    await expect(page.getByRole("heading", { name: "User One" })).toBeVisible({
      timeout: 20000,
    });
    await expect(page.locator("#role")).toHaveCount(0);
    await expect(page.getByLabel("역할")).toHaveCount(0);
  });

  test("should let canonical super admin aliases promote selected users", async ({
    page,
  }) => {
    await page.unroute("**/api/v1/**");
    await page.route("**/api/v1/**", async (route) => {
      const url = route.request().url();
      const headers = { "Access-Control-Allow-Origin": "*" };

      if (url.includes("/user/me")) {
        return route.fulfill({
          json: {
            id: "admin",
            role: "super-admin",
            name: "Admin",
            manageableTenants: [],
          },
          headers,
        });
      }
      if (url.includes("/admin/users")) {
        return route.fulfill({
          json: {
            items: [
              {
                id: "u-1",
                name: "User One",
                email: "u1@test.com",
                status: "active",
                role: "user",
                createdAt: new Date().toISOString(),
              },
            ],
            total: 1,
          },
          headers,
        });
      }
      if (url.includes("/admin/tenants")) {
        return route.fulfill({
          json: { items: [], total: 0 },
          headers,
        });
      }

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

    await page.goto("/users");
    await expect(page.locator("table")).toContainText("User One", {
      timeout: 20000,
    });

    await page.locator('table input[type="checkbox"]').nth(1).click();
    const selectionBar = page.getByTestId("bulk-action-bar");
    await expect(selectionBar).toBeVisible({ timeout: 15000 });
    await expect(page.getByTestId("bulk-permission-select")).toBeVisible();
    await expect(page.getByTestId("bulk-apply-btn")).toBeVisible();
  });

  test("should filter and highlight nodes in organization tree", async ({
    page,
  }) => {
    await page.goto("/tenants/t-1");
    // 테넌트 이름이 제목으로 나올 때까지 대기
    await expect(page.locator("h2").last()).toContainText(
      /Main Tenant|상세|Profile/i,
      { timeout: 20000 },
    );

    const subTenantLink = page
      .locator("a, button")
      .filter({ hasText: /조직 관리|Organization|Sub-tenant/i })
      .first();
    await subTenantLink.click();

    // 트리 검색 입력창 대기 (더 유연한 셀렉터)
    const searchInput = page
      .locator('input[placeholder*="검색"], input[placeholder*="Search"]')
      .first();
    await expect(searchInput).toBeVisible({ timeout: 15000 });

    await searchInput.fill("Eng");

    const engNode = page
      .locator('button, [role="button"]')
      .filter({ hasText: "Engineering" })
      .first();
    await expect(engNode).toBeVisible();
    await expect(engNode).toHaveClass(/bg-primary\/5/);
  });
});
