import { expect, test } from "@playwright/test";
import { installAdminFrontStaticRoutes } from "./helpers/static-adminfront";

test.describe("tenant member removal", () => {
  test.beforeEach(async ({ page }) => {
    await installAdminFrontStaticRoutes(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 clientId = "adminfront";
      const key = `oidc.user:${authority}:${clientId}`;
      window.localStorage.setItem(
        key,
        JSON.stringify({
          access_token: "fake-token",
          token_type: "Bearer",
          profile: {
            sub: "admin-user",
            name: "Admin",
            role: "super_admin",
          },
          expires_at: Math.floor(Date.now() / 1000) + 36000,
        }),
      );
    });
  });

  test("removes a tenant member through the tenant users page", async ({
    page,
  }) => {
    const headers = { "Access-Control-Allow-Origin": "*" };
    const updateRequests: unknown[] = [];

    await page.route("**/oidc/**", async (route) => {
      await route.fulfill({ json: { issuer: "http://localhost:5000/oidc" } });
    });
    await page.route("**/api/v1/user/me", async (route) => {
      await route.fulfill({
        json: {
          id: "admin-user",
          name: "Admin",
          role: "super_admin",
          manageableTenants: [],
        },
        headers,
      });
    });
    await page.route(/.*\/api\/v1\/admin\/tenants(\?.*)?$/, async (route) => {
      await route.fulfill({
        json: {
          items: [
            {
              id: "tenant-team-id",
              name: "기술기획팀",
              slug: "tech-planning",
              type: "USER_GROUP",
              status: "active",
              memberCount: 1,
              totalMemberCount: 1,
              createdAt: "2026-06-10T00:00:00Z",
              updatedAt: "2026-06-10T00:00:00Z",
            },
          ],
          total: 1,
          limit: 100,
          offset: 0,
        },
        headers,
      });
    });
    await page.route("**/api/v1/admin/users**", async (route) => {
      const url = new URL(route.request().url());
      if (
        route.request().method() === "PUT" &&
        url.pathname.endsWith("/api/v1/admin/users/user-1")
      ) {
        updateRequests.push(route.request().postDataJSON());
        await route.fulfill({
          json: { id: "user-1", name: "Alice" },
          headers,
        });
        return;
      }
      if (route.request().method() === "GET") {
        await route.fulfill({
          json: {
            items: [
              {
                id: "user-1",
                name: "Alice",
                email: "alice@example.com",
                role: "user",
                status: "active",
                createdAt: "2026-06-10T00:00:00Z",
                updatedAt: "2026-06-10T00:00:00Z",
              },
            ],
            total: 1,
            limit: 100,
            offset: 0,
          },
          headers,
        });
        return;
      }
      await route.fulfill({ json: {}, headers });
    });

    page.on("dialog", async (dialog) => {
      await dialog.accept();
    });

    await page.goto(
      "http://adminfront.test/tenants/tenant-team-id/organization",
    );
    await expect(
      page.getByRole("cell", { name: "Alice", exact: true }),
    ).toBeVisible();

    await page.getByTestId("tenant-org-member-actions-user-1").click();
    await page.getByTestId("tenant-org-member-remove-user-1").click();

    await expect.poll(() => updateRequests).toHaveLength(1);
    expect(updateRequests[0]).toMatchObject({
      tenantSlug: "tech-planning",
      isRemoveTenant: true,
    });
  });
});
