import assert from "node:assert/strict";
import test from "node:test";
import { access, mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { appendRetainedLog } from "./host-lib.mjs";

test("production logs rotate daily, expire after seven days, stay bounded, and redact before writing", async () => {
  const logsDir = await mkdtemp(join(tmpdir(), "crm-host-logs-"));
  const oldPath = join(logsDir, "backend-2026-07-01.log");
  const recentPath = join(logsDir, "backend-2026-07-16.log");
  await writeFile(oldPath, "old");
  await writeFile(recentPath, "recent");
  await utimes(oldPath, new Date("2026-07-01T00:00:00.000Z"), new Date("2026-07-01T00:00:00.000Z"));
  await utimes(recentPath, new Date("2026-07-16T00:00:00.000Z"), new Date("2026-07-16T00:00:00.000Z"));

  try {
    const path = await appendRetainedLog(logsDir, "backend", "Bearer secret-token at C:\\Users\\operator\\auth.json", {
      now: new Date("2026-07-17T12:00:00.000Z"),
      maxBytes: 80
    });
    const content = await readFile(path, "utf8");

    assert.equal(path, join(logsDir, "backend-2026-07-17.log"));
    await assert.rejects(access(oldPath));
    await access(recentPath);
    assert.equal(content.includes("secret-token"), false);
    assert.equal(content.includes("operator"), false);
    assert.equal(content.includes("auth.json"), false);
    assert.equal(Buffer.byteLength(content, "utf8") <= 80, true);
  } finally {
    await rm(logsDir, { recursive: true, force: true });
  }
});

test("production log expiry attempts are bounded per write", async () => {
  const logsDir = await mkdtemp(join(tmpdir(), "crm-host-log-bound-"));
  await mkdir(logsDir, { recursive: true });
  await Promise.all(Array.from({ length: 40 }, async (_, index) => {
    const path = join(logsDir, `old-${String(index).padStart(2, "0")}.log`);
    await writeFile(path, "old");
    await utimes(path, new Date("2000-01-01T00:00:00.000Z"), new Date("2000-01-01T00:00:00.000Z"));
  }));

  try {
    await appendRetainedLog(logsDir, "backend", "new", { now: new Date("2026-07-17T12:00:00.000Z"), maxCleanup: 32 });
    const oldFiles = (await readdir(logsDir)).filter((name) => name.startsWith("old-"));
    assert.equal(oldFiles.length, 8);
  } finally {
    await rm(logsDir, { recursive: true, force: true });
  }
});
