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

test("derives the public origin from forwarded Cloudflare headers", async () => {
  const { resolvePublicOrigin } = await import("../../lib/server/public-origin.ts");
  const headers = new Headers({
    "x-forwarded-host": "hearbooks-reader.example.workers.dev",
    "x-forwarded-proto": "https",
  });
  assert.equal(resolvePublicOrigin(headers).origin, "https://hearbooks-reader.example.workers.dev");
});

test("uses http only for local development", async () => {
  const { resolvePublicOrigin } = await import("../../lib/server/public-origin.ts");
  assert.equal(resolvePublicOrigin(new Headers({ host: "127.0.0.1:3000" })).origin, "http://127.0.0.1:3000");
  assert.equal(resolvePublicOrigin(new Headers({ host: "hearbooks.example" })).origin, "https://hearbooks.example");
});

test("production sources do not depend on Sites or Cloudflare Images", async () => {
  const [layout, worker] = await Promise.all([
    readFile(new URL("../../app/layout.tsx", import.meta.url), "utf8"),
    readFile(new URL("../../worker/index.ts", import.meta.url), "utf8"),
  ]);
  assert.doesNotMatch(layout, /chatgpt\.site/);
  assert.doesNotMatch(worker, /IMAGES|handleImageOptimization|\/_vinext\/image/);
});
