const { describe, it } = require("node:test");
const assert = require("node:assert");
const fs = require("fs");
const os = require("os");
const path = require("path");
const http = require("http");
const {
  getHealthCheckPorts,
  waitForHealth,
  AGENT_PORT,
} = require("../installer/windows/health-probe");

describe("health-probe", () => {
  it("probes port 5000 only", () => {
    const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "siraya-health-"));
    fs.writeFileSync(path.join(tmp, ".env"), "PORT=5002\n", "utf8");
    fs.writeFileSync(
      path.join(tmp, "settings.json"),
      JSON.stringify({ port: 5001 }),
      "utf8",
    );
    const ports = getHealthCheckPorts(tmp);
    assert.deepEqual(ports, [AGENT_PORT]);
    fs.rmSync(tmp, { recursive: true, force: true });
  });

  it("waits until /health returns 200 on port 5000", async () => {
    const server = http.createServer((req, res) => {
      if (req.url === "/health") {
        res.writeHead(200);
        res.end('{"ok":true}');
        return;
      }
      res.writeHead(404);
      res.end();
    });
    await new Promise((resolve, reject) => {
      server.on("error", reject);
      server.listen(0, "127.0.0.1", resolve);
    });
    const addr = server.address();
    const testPort = typeof addr === "object" && addr ? addr.port : AGENT_PORT;

    const port = await waitForHealth({
      host: "127.0.0.1",
      port: testPort,
      timeoutSec: 5,
    });
    server.close();
    assert.equal(port, testPort);
  });
});
