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

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

import { createApp } from "../../apps/api/src/app.js";

test("a real Edge profile passes the candidate support flow", async ({ browser, context, page }) => {
  const fullVersion = browser.version();
  const release = {
    appVersion: "1.2.3-candidate",
    browsers: [
      { brand: "Google Chrome", fullVersion: "150.0.0.0" },
      { brand: "Microsoft Edge", fullVersion },
    ],
  } as const;
  const app = await createApp({
    browserSupportRelease: release,
    networkBoundary: { allowTestPort: true },
  } as never);
  const url = await app.listen({ host: "127.0.0.1", port: 0 });

  try {
    await page.goto(url);
    await expect.poll(() => page.locator("html").getAttribute("data-support-status")).toBe("supported");
    await expect(page.locator("h1")).toHaveText("浏览器支持检查已通过");
    await expect(page.locator("#status-code")).toBeHidden();
    await expect(page.locator("#no-bypass")).toBeHidden();
    await expect(page.locator("#supported-value")).toContainText("Google Chrome");
    await expect(page.locator("#supported-value")).toContainText("Microsoft Edge");
    const bootstrapStatus = await page.evaluate(async () => (await fetch("/api/v1/bootstrap")).status);
    expect(bootstrapStatus).toBe(200);

    const cookie = (await context.cookies()).find(({ name }) => name === "dada_browser_support");
    expect(cookie).toMatchObject({ httpOnly: true, sameSite: "Strict" });

    const evidenceDirectory = process.env.DADA_EVIDENCE_DIR_BRW_SUPPORTED;
    if (evidenceDirectory) {
      mkdirSync(resolve(evidenceDirectory, "edge", "screenshots"), { recursive: true });
      await page.screenshot({
        path: resolve(evidenceDirectory, "edge", "screenshots", "supported.png"),
      });
      writeFileSync(
        resolve(evidenceDirectory, "edge", "environment.json"),
        `${JSON.stringify({ browser: "Microsoft Edge", full_version: fullVersion, release_kind: "test_candidate", status: "partial" }, null, 2)}\n`,
      );
      writeFileSync(
        resolve(evidenceDirectory, "edge", "response.json"),
        `${JSON.stringify({ bootstrap_status: bootstrapStatus, cookie_http_only: cookie?.httpOnly, status: "passed" }, null, 2)}\n`,
      );
    }
  } finally {
    await app.close();
  }
});

test("the hard-block shell is usable without a product bundle", async ({ browser, page }) => {
  const currentMajor = Number.parseInt(browser.version().split(".")[0], 10);
  const app = await createApp({
    browserSupportRelease: {
      appVersion: "1.2.3-test",
      browsers: [
        { brand: "Google Chrome", fullVersion: `${currentMajor + 1}.0.0.0` },
        { brand: "Microsoft Edge", fullVersion: `${currentMajor + 1}.0.0.0` },
      ],
    },
    networkBoundary: { allowTestPort: true },
  } as never);
  const url = await app.listen({ host: "127.0.0.1", port: 0 });

  try {
    await page.goto(url);
    await expect.poll(() => page.locator("html").getAttribute("data-support-status")).toBe("blocked");
    await expect(page.locator("#reason-value")).toHaveText("version_unsupported");
    await expect(page.getByText("没有“仍然继续”入口，也不会提供绕过令牌或参数。")).toBeVisible();
    await expect(page.locator('script[src*="/src/main"]')).toHaveCount(0);
    await page.keyboard.press("Tab");
    await expect(page.locator("h1")).toBeFocused();
    await page.keyboard.press("Tab");
    await expect(page.locator("summary")).toBeFocused();
    await page.keyboard.press("Tab");
    await expect(page.getByRole("button", { name: "重新检测" })).toBeFocused();
    await page.keyboard.press("Tab");
    await expect(page.getByRole("button", { name: "复制本机地址" })).toBeFocused();

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

    await page.setViewportSize({ height: 844, width: 390 });
    expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
    await expect(page.getByRole("button", { name: "重新检测" })).toBeVisible();
    if (evidenceDirectory) {
      await page.screenshot({ path: resolve(evidenceDirectory, "screenshots", "blocked-mobile.png") });
    }
  } finally {
    await app.close();
  }
});
