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

const liveE2E = process.env.LIVE_BACKEND_E2E === "1";
const oidcAuthority = "https://sso.hmac.kr/oidc";
const clientId = "adminfront";

test.describe("Users CSV live E2E", () => {
  test.skip(!liveE2E, "Set LIVE_BACKEND_E2E=1 to run against a live backend.");

  test.beforeEach(async ({ page, baseURL }) => {
    await page.addInitScript(
      ({ authority, client_id }) => {
        window.localStorage.setItem("locale", "ko");
        window.localStorage.setItem("X-Mock-Role-Enabled", "true");
        window.localStorage.setItem("X-Mock-Role", "super_admin");
        (
          window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }
        )._IS_TEST_MODE = true;

        const key = `oidc.user:${authority}:${client_id}`;
        window.localStorage.setItem(
          key,
          JSON.stringify({
            access_token: "live-e2e-placeholder-token",
            token_type: "Bearer",
            profile: {
              sub: "live-e2e-admin",
              name: "Live E2E Admin",
              role: "super_admin",
            },
            expires_at: Math.floor(Date.now() / 1000) + 3600,
          }),
        );
      },
      { authority: oidcAuthority, client_id: clientId },
    );

    await page.route("**/api/v1/**", async (route) => {
      const requestUrl = new URL(route.request().url());
      const liveUrl = `${baseURL}${requestUrl.pathname}${requestUrl.search}`;
      const { authorization: _authorization, ...headers } = route
        .request()
        .headers();
      headers["x-test-role"] = "super_admin";
      const response = await route.fetch({ url: liveUrl, headers });
      await route.fulfill({ response });
    });

    await page.route("**/oidc/**", async (route) => {
      await route.fulfill({
        json: {
          issuer: oidcAuthority,
          authorization_endpoint: `${oidcAuthority}/auth`,
          token_endpoint: `${oidcAuthority}/token`,
          jwks_uri: `${oidcAuthority}/jwks`,
          userinfo_endpoint: `${oidcAuthority}/userinfo`,
          end_session_endpoint: `${oidcAuthority}/session/end`,
        },
      });
    });
  });

  test("exports user CSV through the authenticated admin UI path", async ({
    page,
  }) => {
    await page.goto("/users");
    await expect(page.getByTestId("page-title")).toContainText(/사용자|Users/i);

    const downloadPromise = page.waitForEvent("download");
    await page.getByRole("button", { name: /내보내기|Export/i }).click();
    const download = await downloadPromise;

    expect(download.suggestedFilename()).toContain("users");
    const path = await download.path();
    expect(path).toBeTruthy();

    const csv = fs.readFileSync(path as string, "utf8");
    expect(csv).toContain(
      "ID,Email,Name,Phone,Status,Tenant,Position,JobTitle,CreatedAt",
    );
    expect(csv).not.toContain("Role");
    expect(csv).not.toContain("Department");
  });
});
