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

test("Wildcard preview addresses keep HTTP after canonicalization", 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 health OK</title><body style="font:24px system-ui;padding:32px">plain HTTP health OK</body>');
  });
  await new Promise<void>((resolve) => server.listen(44605, "0.0.0.0", resolve));
  try {
    const project = await t3.project("preview-demo");
    const thread = await t3.thread({ project, title: "Wildcard HTTP preview", model: "default", 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 values: string[] = [];
    for (const [label, input] of [
      ["trailing-dot", "0.0.0.0.:44605/health"],
      ["control", "0.0.0.0:44605/health"],
      ["query", "0.0.0.0?debug=1"],
      ["explicit-https", "https://0.0.0.0:44605/health"],
    ]) {
      await address.fill(input!);
      await browser.keyboard.press("Enter");
      await screen.getByRole("button", "Refresh", { exact: true }).waitFor();
      values.push(await address.inputValue());
      await app.screenshot(label!);
    }
    expect(values).toEqual([
      "http://0.0.0.0:44605/health", "http://0.0.0.0:44605/health",
      "http://0.0.0.0/?debug=1", "https://0.0.0.0:44605/health",
    ]);
  } finally {
    server.closeAllConnections();
    await new Promise((resolve) => server.close(resolve));
  }
});
