import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import test from "node:test";
import { resolveVaultPaths, type PiSshConfig } from "../src/config.ts";
import { saveVault } from "../src/vault.ts";

const fixture: PiSshConfig = {
  version: 1,
  hosts: {
    packaging: {
      label: "Packaging",
      hostName: "192.0.2.15",
      user: "builder",
      port: 22,
      auth: { type: "password", password: "never-print-this" },
      hostKey: { algorithm: "ssh-ed25519", fingerprint: "SHA256:fixture" },
    },
  },
};

test("the configuration CLI lists hosts without revealing credentials", () => {
  const home = mkdtempSync(join(tmpdir(), "pi-ssh-cli-"));
  const configHome = join(home, "config");
  saveVault(fixture, resolveVaultPaths({ XDG_CONFIG_HOME: configHome }, process.platform, home));
  const result = spawnSync(resolve("../ssh_config.sh"), ["list"], {
    encoding: "utf8",
    env: { ...process.env, HOME: home, XDG_CONFIG_HOME: configHome },
  });
  assert.equal(result.status, 0, result.stderr);
  assert.match(result.stdout, /packaging\s+Packaging\s+builder@192\.0\.2\.15:22\s+password/);
  assert.doesNotMatch(`${result.stdout}${result.stderr}`, /never-print-this/);
});
