import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";

import { isPwaEventStreamRequest, pwaAllowedHosts, pwaProxyOrigin } from "./vite-hosts.js";

test("pwaAllowedHosts defaults to no machine-specific hosts", () => {
  assert.deepEqual(pwaAllowedHosts({}), []);
});

test("pwaAllowedHosts reads a comma-separated local environment override", () => {
  assert.deepEqual(
    pwaAllowedHosts({ CODE_REMOTE_MANAGER_PWA_ALLOWED_HOSTS: "phone.tailnet.ts.net, desktop.tailnet.ts.net " }),
    ["phone.tailnet.ts.net", "desktop.tailnet.ts.net"]
  );
});

test("vite config does not commit a real machine-specific tailnet host", async () => {
  const source = await readFile(new URL("./vite.config.js", import.meta.url), "utf8");
  assert.equal(/tail[0-9a-f]+\.ts\.net/i.test(source), false);
});

test("pwaProxyOrigin restores the configured HTTPS origin for same-origin proxy requests", () => {
  const env = { CODE_REMOTE_MANAGER_PWA_ALLOWED_HOSTS: "operator.example.ts.net" };
  assert.equal(pwaProxyOrigin({ headers: { host: "operator.example.ts.net" } }, env), "https://operator.example.ts.net");
  assert.equal(
    pwaProxyOrigin({ headers: { host: "operator.example.ts.net", "x-forwarded-proto": "https" } }, env),
    "https://operator.example.ts.net"
  );
});

test("pwaProxyOrigin supports local development and rejects unconfigured hosts", () => {
  assert.equal(pwaProxyOrigin({ headers: { host: "127.0.0.1:43111" } }, {}), "http://127.0.0.1:43111");
  assert.equal(pwaProxyOrigin({ headers: { host: "localhost:43111" } }, {}), "http://localhost:43111");
  assert.equal(pwaProxyOrigin({ headers: { host: "attacker.example" } }, {}), "");
});

test("only session event-stream proxy paths receive a restored origin", () => {
  assert.equal(isPwaEventStreamRequest("GET", "/api/sessions/events"), true);
  assert.equal(isPwaEventStreamRequest("GET", "/api/sessions/session-1/events?cursor=1"), true);
  assert.equal(isPwaEventStreamRequest("GET", "/sessions/events"), true);
  assert.equal(isPwaEventStreamRequest("GET", "/sessions/session-1/events?cursor=1"), true);
  assert.equal(isPwaEventStreamRequest("GET", "/api/sessions"), false);
  assert.equal(isPwaEventStreamRequest("POST", "/api/sessions/session-1/events"), false);
});
