import * as NodeHttp from "node:http";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Localhost subdomains open the plain HTTP development server", WEB, async ({ t3, app, browser, screen }) => {
  const server = NodeHttp.createServer((_request, response) => {
    response.writeHead(200, { "content-type": "text/html" });
    response.end('<!doctype html><title>Plain HTTP dev server OK</title><body style="font:24px system-ui;padding:32px;background:#effaf1;color:#143d20"><h1>Plain HTTP dev server OK</h1><p>This development page is served over plain HTTP.</p></body>');
  });
  await new Promise<void>((resolve) => server.listen(8000, "127.0.0.1", resolve));
  try {
    const project = await t3.project("demo");
    const thread = await t3.thread({ project, title: "Localhost development preview", messages: ["first"] });
    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel").tap();
    await screen.getByRole("button", "Browser B").tap();
    const address = screen.getByRole("textbox", "Search or enter URL");
    const actual: string[] = [];
    for (const [label, input] of [
      ["app-localhost", "app.localhost:8000"],
      ["nested-localhost", "api.app.localhost:8000"],
      ["explicit-http-control", "http://app.localhost:8000"],
      ["bare-localhost-control", "localhost:8000"],
      ["explicit-https-preserved", "https://app.localhost:8000"],
    ]) {
      await address.fill(input!);
      await browser.keyboard.press("Enter");
      await expect.poll(() => browser.evaluate(() => {
        const input = document.querySelector<HTMLInputElement>('input[aria-label="Search or enter URL"]');
        return input?.value ?? "";
      })).toMatch(/^https?:\/\//);
      await screen.getByText(/Plain HTTP dev server OK|This site can.t be reached/).first().waitFor();
      actual.push(await browser.evaluate(() => document.querySelector<HTMLInputElement>('input[aria-label="Search or enter URL"]')!.value));
      await app.screenshot(label!);
    }
    expect(actual).toEqual([
      "http://app.localhost:8000/", "http://api.app.localhost:8000/",
      "http://app.localhost:8000/", "http://localhost:8000/", "https://app.localhost:8000/",
    ]);
  } finally {
    server.closeAllConnections();
    await new Promise<void>((resolve) => server.close(() => resolve()));
  }
});
