import assert from "node:assert/strict";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { EdgeState } from "../src/state.mjs";

test("stores only renewable device grants and never cloud TIDs", async () => {
  const directory = await fs.mkdtemp(path.join(os.tmpdir(), "vimify-edge-test-"));
  const state = new EdgeState(directory);
  await state.load();
  const deviceHash = "a".repeat(64);
  const leaseExpiresAt = new Date(Date.now() + 15 * 60_000).toISOString();
  await state.applySync({
    ok: true,
    hotspotId: "hotspot-1",
    cursor: 14,
    authorizations: [{
      version: 1,
      voucherId: "voucher-internal-id",
      hotspotId: "hotspot-1",
      deviceHash,
      status: "active",
      grant: "signed.token",
      expiresAt: new Date(Date.now() + 86_400_000).toISOString(),
      leaseExpiresAt,
      transactionId: "THIS-MUST-NOT-BE-PERSISTED",
    }],
  }, "hotspot-1");

  assert.equal(state.getGrant(deviceHash)?.voucherId, "voucher-internal-id");
  assert.equal(state.data.cursor, 14);
  const persisted = await fs.readFile(path.join(directory, "state.json"), "utf8");
  assert.equal(persisted.includes("THIS-MUST-NOT-BE-PERSISTED"), false);
  await fs.rm(directory, { recursive: true, force: true });
});

test("removes expired leases and acknowledges queued accounting", async () => {
  const directory = await fs.mkdtemp(path.join(os.tmpdir(), "vimify-edge-test-"));
  const state = new EdgeState(directory);
  await state.load();
  state.data.grants["b".repeat(64)] = { leaseExpiresAt: new Date(0).toISOString(), expiresAt: new Date(0).toISOString() };
  state.pruneExpired();
  assert.equal(Object.keys(state.data.grants).length, 0);
  await state.queueAccounting({ accountingSessionId: "one" });
  await state.queueAccounting({ accountingSessionId: "two" });
  await state.acknowledgeAccounting(1);
  assert.deepEqual(state.accountingBatch(), [{ accountingSessionId: "two" }]);
  await fs.rm(directory, { recursive: true, force: true });
});
