"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { receiveBundle } = require("./repo-push-broker");

test("receiver permits only an allowlisted fast-forward bundle with an exact base", async () => {
  const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), "lake-lamp-upload-"));
  const bundle = path.join(uploadDir, "one.bundle"); fs.writeFileSync(bundle, "bundle");
  const calls = [];
  const base = "a".repeat(40), incoming = "b".repeat(40);
  const run = async args => { calls.push(args); if (args.includes("rev-parse")) return { ok: true, stdout: `${incoming}\n` }; if (args[0] === "ls-remote") return { ok: true, stdout: `${base}\trefs/heads/main\n` }; return { ok: true, stdout: "" }; };
  try {
    const result = await receiveBundle({ repo: "bingshuo/guanghu-ice-heart", branch: "main", expected_head: base, bundle_path: bundle }, { uploadDir, registry: { "bingshuo/guanghu-ice-heart": { branch: "main", remote: "http://local/code.git", verification_url: "https://example.invalid/commits/main" } }, run });
    assert.equal(result.ok, true); assert.equal(result.commit_sha, incoming);
    assert.ok(calls.some(args => args.includes("push")));
  } finally { fs.rmSync(uploadDir, { recursive: true, force: true }); }
});

test("receiver refuses a changed remote base before it can push", async () => {
  const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), "lake-lamp-upload-"));
  const bundle = path.join(uploadDir, "one.bundle"); fs.writeFileSync(bundle, "bundle");
  const base = "a".repeat(40), changed = "c".repeat(40);
  const run = async args => { if (args.includes("rev-parse")) return { ok: true, stdout: `${"b".repeat(40)}\n` }; if (args[0] === "ls-remote") return { ok: true, stdout: `${changed}\trefs/heads/main\n` }; if (args.includes("push")) throw new Error("must not push"); return { ok: true, stdout: "" }; };
  try {
    const result = await receiveBundle({ repo: "bingshuo/guanghu-ice-heart", branch: "main", expected_head: base, bundle_path: bundle }, { uploadDir, registry: { "bingshuo/guanghu-ice-heart": { branch: "main", remote: "http://local/code.git" } }, run });
    assert.equal(result.diagnostic_code, "expected_head_mismatch");
  } finally { fs.rmSync(uploadDir, { recursive: true, force: true }); }
});
