import assert from "node:assert/strict";
import test from "node:test";
import { writeSafeLog } from "./safe-logger.js";

test("structured operational logs sanitize errors, credentials, cookies, and local paths", () => {
  const lines = [];
  const logger = {
    warn(line) { lines.push(line); }
  };
  const error = new Error("Bearer log-secret at C:\\Users\\operator\\.codex\\auth.json");
  error.cookieHeader = "device_session=cookie-secret";

  writeSafeLog(logger, "warn", "request_rejected", { error }, {});

  assert.equal(lines.length, 1);
  for (const secret of ["log-secret", "cookie-secret", "operator", "auth.json"]) {
    assert.equal(lines[0].includes(secret), false, secret);
  }
  assert.equal(JSON.parse(lines[0]).code, "request_rejected");
});

test("operational logging fails closed when structured sanitization cannot read input", () => {
  const lines = [];
  const logger = {
    error(line) { lines.push(line); }
  };
  const unsafe = {};
  Object.defineProperty(unsafe, "value", {
    enumerable: true,
    get() { throw new Error("Bearer fallback-secret"); }
  });

  writeSafeLog(logger, "error", "runtime_failure", unsafe, {});

  assert.equal(lines.length, 1);
  assert.deepEqual(JSON.parse(lines[0]), { level: "error", code: "log_sanitization_failed" });
  assert.equal(lines[0].includes("fallback-secret"), false);
});
