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

test.describe("Tenant Allowed Domains", () => {
  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}`;
      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,
        }),
      );
    });

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

  test("adds samaneng.com to the current tenant after duplicate warning confirmation", async ({
    page,
  }) => {
    let savedPayload:
      | {
          domains?: string[];
          forceDomainConflicts?: string[];
        }
      | 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/current") && method === "GET") {
        return route.fulfill({
          json: {
            id: "current",
            name: "현재 테넌트",
            slug: "current",
            type: "COMPANY",
            description: "",
            status: "active",
            domains: [],
            memberCount: 0,
            createdAt: "",
            updatedAt: "",
          },
          headers,
        });
      }

      if (url.includes("/admin/tenants/current") && method === "PUT") {
        savedPayload = route.request().postDataJSON();
        return route.fulfill({
          json: {
            id: "current",
            name: "현재 테넌트",
            slug: "current",
            type: "COMPANY",
            description: "",
            status: "active",
            domains: savedPayload?.domains ?? [],
            memberCount: 0,
            createdAt: "",
            updatedAt: "",
          },
          headers,
        });
      }

      if (url.includes("/admin/tenants")) {
        return route.fulfill({
          json: {
            items: [
              {
                id: "current",
                name: "현재 테넌트",
                slug: "current",
                type: "COMPANY",
                description: "",
                status: "active",
                domains: [],
                memberCount: 0,
                createdAt: "",
                updatedAt: "",
              },
              {
                id: "existing",
                name: "한맥가족",
                slug: "hanmac-family",
                type: "COMPANY",
                description: "",
                status: "active",
                domains: ["samaneng.com"],
                memberCount: 0,
                createdAt: "",
                updatedAt: "",
              },
            ],
            total: 2,
            limit: 1000,
            offset: 0,
          },
          headers,
        });
      }

      return route.fulfill({ json: {}, headers });
    });

    await page.goto("/tenants/current");
    await page.locator("#tenant-domains").fill("samaneng.com");
    await page.keyboard.press("Space");

    await expect(
      page.getByText(
        "samaneng.com 도메인은 한맥가족 테넌트에 이미 설정되어 있습니다. 그래도 현재 테넌트에도 추가하시겠습니까?",
      ),
    ).toBeVisible();

    await page.getByRole("button", { name: "계속 진행" }).click();
    await expect(page.getByText("samaneng.com")).toBeVisible();

    await page.getByRole("button", { name: "저장" }).click();

    await expect
      .poll(() => savedPayload)
      .toMatchObject({
        domains: ["samaneng.com"],
        forceDomainConflicts: ["samaneng.com"],
      });
  });
});
