/**
 * @file Tests for server/lib/named-lock.js: cross-lane named locks — mkdir
 * atomicity, the LOCK_MAX_HOLD staleness floor, holder-checked release, and
 * status/listing.
 * @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
 */

const os = require("node:os");
const path = require("node:path");
const fs = require("node:fs");
const { describe, it, after, beforeEach } = require("node:test");
const assert = require("node:assert/strict");

const SUITE_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-named-lock-"));
process.env.LANES_ROOT = SUITE_ROOT;
after(() => fs.rmSync(SUITE_ROOT, { recursive: true, force: true }));

const namedLock = require("../lib/named-lock");

beforeEach(() => {
  fs.rmSync(namedLock.locksRoot(), { recursive: true, force: true });
  delete process.env.LOCK_MAX_HOLD;
});

describe("tryAcquire / release", () => {
  it("acquires a free lock and reports it held afterward", () => {
    const result = namedLock.tryAcquire("build", "lane1");
    assert.deepEqual(result, { acquired: true });
    const status = namedLock.status("build");
    assert.equal(status.held, true);
    assert.equal(status.holder, "lane1");
  });

  it("a second acquire on the same name reports not-acquired with the current holder", () => {
    namedLock.tryAcquire("build", "lane1");
    const second = namedLock.tryAcquire("build", "lane2");
    assert.equal(second.acquired, false);
    assert.equal(second.holder, "lane1");
  });

  it("a second acquire succeeds after release", () => {
    namedLock.tryAcquire("build", "lane1");
    namedLock.release("build", "lane1");
    const second = namedLock.tryAcquire("build", "lane2");
    assert.equal(second.acquired, true);
    assert.equal(namedLock.status("build").holder, "lane2");
  });

  it("release from a non-holder is refused and leaves the lock held", () => {
    namedLock.tryAcquire("build", "lane1");
    assert.throws(
      () => namedLock.release("build", "lane2"),
      (err) => err.code === "ENOTHOLDER"
    );
    assert.equal(namedLock.status("build").held, true);
    assert.equal(namedLock.status("build").holder, "lane1");
  });

  it("releasing a lock that doesn't exist throws ENOLOCK", () => {
    assert.throws(
      () => namedLock.release("never-held", "lane1"),
      (err) => err.code === "ENOLOCK"
    );
  });
});

describe("staleness with a floor", () => {
  /** Back-date a lock's owner file by writing it directly, bypassing tryAcquire's "now". */
  function backdate(name, holder, ageSec) {
    const dir = path.join(namedLock.locksRoot(), name);
    fs.mkdirSync(dir, { recursive: true });
    const since = Math.floor(Date.now() / 1000) - ageSec;
    fs.writeFileSync(path.join(dir, "owner"), `${holder} ${since}`);
  }

  it("a holder older than LOCK_MAX_HOLD is broken on the next acquire", () => {
    backdate("stale", "lane1", 2701); // just past the 2700s default
    const result = namedLock.tryAcquire("stale", "lane2");
    assert.equal(result.acquired, true);
    assert.equal(namedLock.status("stale").holder, "lane2");
  });

  it("a holder backdated within the 300s floor is NOT broken, even with LOCK_MAX_HOLD=1", () => {
    process.env.LOCK_MAX_HOLD = "1";
    backdate("floor-test", "lane1", 100); // within the 300s floor
    const result = namedLock.tryAcquire("floor-test", "lane2");
    assert.equal(result.acquired, false);
    assert.equal(result.holder, "lane1");
  });

  it("a holder older than a LOCK_MAX_HOLD set above the floor is broken", () => {
    process.env.LOCK_MAX_HOLD = "400";
    backdate("above-floor", "lane1", 401);
    const result = namedLock.tryAcquire("above-floor", "lane2");
    assert.equal(result.acquired, true);
  });
});

describe("listLocks", () => {
  it("lists every currently-held lock", () => {
    namedLock.tryAcquire("build", "lane1");
    namedLock.tryAcquire("e2e", "lane2");
    const locks = namedLock.listLocks().sort((a, b) => a.name.localeCompare(b.name));
    assert.deepEqual(
      locks.map((l) => [l.name, l.holder]),
      [
        ["build", "lane1"],
        ["e2e", "lane2"],
      ]
    );
  });

  it("returns an empty array when no locks exist", () => {
    assert.deepEqual(namedLock.listLocks(), []);
  });
});
