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

const tenants = [
  {
    id: "038326b6-954a-48a7-a85f-efd83f62b82a",
    name: "한맥가족",
    slug: "hanmac-family",
    type: "COMPANY_GROUP",
    description: "한맥가족 기본 루트 테넌트",
    status: "active",
    domains: [],
    memberCount: 0,
    createdAt: "",
    updatedAt: "",
  },
  {
    id: "5a03efd2-e62f-4243-800d-58334bf48b2f",
    name: "한라산업개발",
    slug: "hallasanup",
    type: "COMPANY",
    description: "네이버웍스 한라 HALLA_DOMAIN_ID",
    status: "active",
    domains: ["hallasanup.com"],
    memberCount: 0,
    parentId: "038326b6-954a-48a7-a85f-efd83f62b82a",
    createdAt: "",
    updatedAt: "",
  },
  {
    id: "normal-tenant",
    name: "일반 테넌트",
    slug: "normal-tenant",
    type: "COMPANY",
    description: "",
    status: "active",
    domains: [],
    memberCount: 0,
    createdAt: "",
    updatedAt: "",
  },
];

test.describe("Seed tenant protection", () => {
  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" } });
    });

    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-user",
            name: "Admin",
            role: "super_admin",
            manageableTenants: [],
          },
          headers,
        });
      }

      if (url.includes("/admin/tenants/seed-hanmac")) {
        return route.fulfill({ json: tenants[0], headers });
      }

      if (url.includes("/admin/tenants")) {
        return route.fulfill({
          json: {
            items: tenants,
            total: tenants.length,
            limit: 1000,
            offset: 0,
          },
          headers,
        });
      }

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

  test("removes selection and disables delete action for seed tenants in the list", async ({
    page,
  }) => {
    await page.goto("/tenants");

    const seedRow = page.getByRole("row").filter({
      has: page.getByRole("link", { name: "한맥가족", exact: true }),
    });
    await expect(seedRow.getByRole("checkbox")).toHaveCount(0);
    await expect(seedRow.getByText("초기 설정")).toBeVisible();

    const hallaRow = page.getByRole("row").filter({
      has: page.getByRole("link", { name: "한라산업개발", exact: true }),
    });
    await expect(hallaRow.getByRole("checkbox")).toHaveCount(0);
    await expect(hallaRow.getByText("초기 설정")).toBeVisible();

    const normalRow = page.getByRole("row").filter({
      has: page.getByRole("link", { name: "일반 테넌트", exact: true }),
    });
    await expect(normalRow.getByRole("checkbox")).toBeEnabled();
  });

  test("disables delete action on seed tenant profile", async ({ page }) => {
    await page.goto("/tenants/seed-hanmac");

    await expect(page.getByRole("heading", { name: "한맥가족" })).toBeVisible();
    await expect(page.getByRole("button", { name: "삭제" })).toBeDisabled();
  });
});
