import { mkdirSync } from "node:fs";
import { resolve } from "node:path";

import { expect, test } from "@playwright/test";
import { createServer, type ViteDevServer } from "vite";

let vite: ViteDevServer;
let webUrl: string;

test.beforeAll(async () => {
  vite = await createServer({
    configFile: resolve("apps/web/vite.config.ts"),
    root: resolve("apps/web"),
    server: { host: "127.0.0.1", port: 0 },
  });
  await vite.listen();
  const address = vite.httpServer?.address();
  if (!address || typeof address === "string") throw new Error("Vite did not expose a test port.");
  webUrl = `http://127.0.0.1:${address.port}`;
});

test.afterAll(async () => vite.close());

test("TDD-WP1-AUTH-004 purges the opened surface on session invalidation", async ({ page }) => {
  await page.goto(webUrl);
  await expect(page.getByRole("heading", { name: "邮箱验证码登录" })).toBeVisible();
  const email = page.getByLabel("邮箱");
  await email.fill("private-local-state");
  await expect(email).toHaveValue("private-local-state");

  await page.evaluate(() => {
    window.dispatchEvent(new Event("dada:session-invalid"));
  });

  await expect(page.getByRole("heading", { name: "邮箱验证码登录" })).toBeVisible();
  await expect(page.getByLabel("邮箱")).toHaveValue("");

  const evidenceDirectory = process.env.DADA_EVIDENCE_DIR_AUTH_REVOKE;
  if (evidenceDirectory) {
    mkdirSync(resolve(evidenceDirectory, "screenshots"), { recursive: true });
    await page.screenshot({ fullPage: true, path: resolve(evidenceDirectory, "screenshots", "revoked.png") });
  }
});
