"use strict";

const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const test = require("node:test");
const { validPush, verifySignature } = require("../sync-agent");

const config = { repository_full_name: "bingshuo/fifth-domain", allowed_ref: "refs/heads/main" };
const good = { ref: "refs/heads/main", after: "a".repeat(40), repository: { full_name: "bingshuo/fifth-domain" } };

test("verifies Forgejo HMAC signatures", () => {
  const secret = "a".repeat(32);
  const body = Buffer.from('{"ok":true}');
  const signature = crypto.createHmac("sha256", secret).update(body).digest("hex");
  assert.equal(verifySignature(secret, body, signature), true);
  assert.equal(verifySignature(secret, body, "0".repeat(64)), false);
});

test("accepts only the registered Fifth Domain main push", () => {
  assert.equal(validPush(good, config), true);
  assert.equal(validPush({ ...good, ref: "refs/heads/feature" }, config), false);
  assert.equal(validPush({ ...good, repository: { full_name: "other/repo" } }, config), false);
  assert.equal(validPush({ ...good, after: "not-a-commit" }, config), false);
});
