/**
 * Focused tests for reset authorization and coordinator state wipe.
 * Run: node reset_auth.test.js
 */
const assert = require("assert");
const path = require("path");

const TOKEN = "test-reset-token-not-for-production";
process.env.SARMAD_RESET_TOKEN = TOKEN;

const {
  authorizeReset,
  createGenesisCycle,
  resetCoordinatorState,
  getResetToken,
  _test,
} = require(path.join(__dirname, "server.js"));

function reqWithHeader(value) {
  const headers = {};
  if (value !== undefined) headers["x-sarmad-reset-token"] = value;
  return { headers };
}

assert.strictEqual(getResetToken(), TOKEN);

assert.deepStrictEqual(authorizeReset(reqWithHeader(TOKEN)), { ok: true });
assert.strictEqual(authorizeReset(reqWithHeader(undefined)).code, 403);
assert.strictEqual(authorizeReset(reqWithHeader("")).code, 403);
assert.strictEqual(authorizeReset(reqWithHeader("wrong-token")).code, 403);

const prev = process.env.SARMAD_RESET_TOKEN;
delete process.env.SARMAD_RESET_TOKEN;
assert.strictEqual(authorizeReset(reqWithHeader(TOKEN)).code, 503);
process.env.SARMAD_RESET_TOKEN = prev;

_test.seedNode("SRMD1TEST");
_test.getCycle().chainHeight = 42;
_test.getCycle().completed.push("SRMD1TEST");
assert.strictEqual(_test.nodes.size, 1);
assert.strictEqual(_test.getCycle().chainHeight, 42);

resetCoordinatorState();
assert.strictEqual(_test.nodes.size, 0);
const c = _test.getCycle();
const genesis = createGenesisCycle();
assert.strictEqual(c.cycleId, genesis.cycleId);
assert.strictEqual(c.chainHeight, 0);
assert.strictEqual(c.tipHash, genesis.tipHash);
assert.strictEqual(c.seed, genesis.seed);
assert.deepStrictEqual(c.activeNodes, []);
assert.deepStrictEqual(c.completed, []);
assert.strictEqual(c.tipTimestamp, 0);
assert.strictEqual(c.blockTimeSeconds, genesis.blockTimeSeconds);

console.log("reset_auth.test.js: ok");
