import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createUsageHistoryStore } from "./usage-history.js";

test("usage history persists only safe account limit snapshots", async () => {
  const dir = await mkdtemp(join(tmpdir(), "usage-history-"));
  try {
    const store = createUsageHistoryStore(dir);
    const usage = {
      primary: { remainingPercent: 72, resetsAt: "2026-07-14T05:00:00.000Z" },
      secondary: { remainingPercent: 41, resetsAt: "2026-07-18T00:00:00.000Z" },
      resetCreditsAvailable: 1,
      secret: "must-not-persist"
    };
    await store.record("account-a", usage, new Date("2026-07-14T01:00:00.000Z"));

    assert.deepEqual(await store.history("account-a", new Date("2026-07-01T00:00:00.000Z")), [{
      at: "2026-07-14T01:00:00.000Z",
      primaryRemainingPercent: 72,
      primaryResetsAt: "2026-07-14T05:00:00.000Z",
      secondaryRemainingPercent: 41,
      secondaryResetsAt: "2026-07-18T00:00:00.000Z"
    }]);
    const persisted = await readFile(join(dir, "usage-history.json"), "utf8");
    assert.doesNotMatch(persisted, /secret|must-not-persist|codexHome|path/i);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
});

test("usage history coalesces unchanged samples and retains changed values", async () => {
  const store = createUsageHistoryStore("");
  const usage = { primary: { remainingPercent: 80 }, secondary: { remainingPercent: 60 } };
  await store.record("a", usage, new Date("2026-07-14T01:00:00.000Z"));
  await store.record("a", usage, new Date("2026-07-14T01:01:00.000Z"));
  await store.record("a", { ...usage, primary: { remainingPercent: 79 } }, new Date("2026-07-14T01:02:00.000Z"));

  const points = await store.history("a", new Date("2026-07-14T00:00:00.000Z"));
  assert.equal(points.length, 2);
  assert.equal(points[1].primaryRemainingPercent, 79);
});

test("usage history keeps account IDs isolated even when they represent the same login", async () => {
  const store = createUsageHistoryStore("");
  const at = new Date("2026-07-14T01:00:00.000Z");
  await store.record("account-a", { primary: { remainingPercent: 80 } }, at);
  await store.record("account-b", { primary: { remainingPercent: 35 } }, at);

  assert.equal((await store.history("account-a"))[0].primaryRemainingPercent, 80);
  assert.equal((await store.history("account-b"))[0].primaryRemainingPercent, 35);
});
