"use strict";

const assert = require("node:assert/strict");
const test = require("node:test");
const { createApp } = require("../server");
const fs = require("node:fs");
const path = require("node:path");

test("JD hub exposes a minimal non-secret status response", async (t) => {
  const server = createApp().listen(0, "127.0.0.1");
  t.after(() => server.close());
  await new Promise((resolve) => server.once("listening", resolve));
  const { port } = server.address();
  const response = await fetch(`http://127.0.0.1:${port}/api/status`);
  assert.equal(response.status, 200);
  const body = await response.json();
  assert.equal(body.ok, true);
  assert.equal(body.node_id, "JD-FD-PRIMARY");
  assert.equal("ip" in body, false);
  assert.equal("token" in body, false);
});

test("JD hub serves its application page", async (t) => {
  const server = createApp().listen(0, "127.0.0.1");
  t.after(() => server.close());
  await new Promise((resolve) => server.once("listening", resolve));
  const { port } = server.address();
  const response = await fetch(`http://127.0.0.1:${port}/`);
  assert.equal(response.status, 200);
  assert.match(await response.text(), /京东云主节点/);
});

test("tunnel service keeps private addresses outside the repository", () => {
  const unit = fs.readFileSync(path.join(__dirname, "..", "guanghu-jd-web-tunnel.service"), "utf8");
  assert.match(unit, /\/etc\/guanghu\/jd-web-tunnel-ssh-config/);
  assert.doesNotMatch(unit, /(?:\d{1,3}\.){3}\d{1,3}/);
});
