import { createReadStream } from "node:fs";
import { createServer } from "node:http";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

const root = dirname(fileURLToPath(import.meta.url));
const port = Number(process.env.PORT ?? 8080);
const files = new Map([
  ["/", ["tests/tests.html", "text/html; charset=utf-8"]],
  ["/tests.html", ["tests/tests.html", "text/html; charset=utf-8"]],
  ["/sdk/contractless.js", ["sdk/contractless.js", "text/javascript; charset=utf-8"]]
]);

const server = createServer((request, response) => {
  const pathname = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
  const target = files.get(pathname);
  if (!target) {
    response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
    response.end("Not found");
    return;
  }

  response.writeHead(200, {
    "Content-Type": target[1],
    "Cache-Control": "no-store",
    "X-Content-Type-Options": "nosniff"
  });
  createReadStream(join(root, target[0])).pipe(response);
});

server.listen(port, "127.0.0.1", () => {
  console.log(`Contractless wallet test: http://127.0.0.1:${port}/tests.html`);
});
