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

test.describe("Tenant Owners Management", () => {
  test.beforeEach(async ({ page }) => {
    await page.addInitScript(() => {
      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 User",
          email: "admin@example.com",
          role: "super_admin",
        },
        expires_at: Math.floor(Date.now() / 1000) + 36000,
      };
      window.localStorage.setItem(key, JSON.stringify(authData));
      window.localStorage.setItem("admin_session", "fake-token");
      window.localStorage.setItem("locale", "ko");
      (
        window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }
      )._IS_TEST_MODE = true;
    });

    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();
      if (url.includes("/user/me")) {
        console.log("Mocking ME");
        return route.fulfill({
          json: {
            id: "admin-user",
            name: "Admin User",
            email: "admin@example.com",
            role: "super_admin",
            manageableTenants: [],
          },
        });
      }
      if (url.includes("/owners")) {
        return route.fulfill({
          json: [
            { id: "owner-1", name: "Owner One", email: "owner1@example.com" },
          ],
        });
      }
      if (url.includes("/admins")) {
        return route.fulfill({ json: [] });
      }
      if (url.includes("/admin/tenants/tenant-1")) {
        return route.fulfill({
          json: {
            id: "tenant-1",
            name: "Test Tenant",
            slug: "test-tenant",
            status: "active",
            type: "COMPANY",
          },
        });
      }
      if (url.includes("/admin/users") && route.request().method() === "GET") {
        return route.fulfill({
          json: {
            items: [
              { id: "user-2", name: "User Two", email: "user2@example.com" },
            ],
            total: 1,
          },
        });
      }
      if (route.request().method() === "GET") {
        return route.fulfill({ json: { items: [], total: 0 } });
      }
      return route.fulfill({ status: 200, json: {} });
    });
  });

  test("should list tenant owners", async ({ page }) => {
    await page.goto("/tenants/tenant-1/permissions");

    await expect(page.locator(".animate-spin").first()).not.toBeVisible();

    await expect(page.getByText(/테넌트 소유자|Tenant Owners/)).toBeVisible();
    await expect(page.locator("table").first()).toContainText("Owner One");
    await expect(page.locator("table").first()).toContainText(
      "owner1@example.com",
    );
  });

  test("should add a new owner", async ({ page }) => {
    // Specific override for this test
    await page.route(
      "**/api/v1/admin/tenants/tenant-1/owners",
      async (route) => {
        if (route.request().method() === "GET") {
          await route.fulfill({ json: [] });
        } else {
          await route.fulfill({ status: 200, json: {} });
        }
      },
    );

    await page.goto("/tenants/tenant-1/permissions");

    await expect(page.locator(".animate-spin").first()).not.toBeVisible();

    await page.click(
      'button:has-text("소유자 추가"), button:has-text("Add Owner")',
    );
    await page.fill(
      'input[placeholder*="사용자 검색"], input[placeholder*="Search users"]',
      "User Two",
    );

    const addButton = page
      .locator("role=dialog")
      .getByRole("button", { name: /추가|Add/ });
    await addButton.click();

    await expect(page.getByText("소유자가 추가되었습니다.")).toBeVisible();
    await expect(page.locator("table").first()).toContainText("User Two");
    await page.waitForTimeout(1200);
    await expect(page.locator("table").first()).toContainText("User Two");
  });
});
