"use strict";

const assert = require("node:assert/strict");
const { execFileSync } = require("node:child_process");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");

const root = path.resolve(__dirname, "..");
const readJson = relative => JSON.parse(fs.readFileSync(path.join(root, relative), "utf8"));

test("every bridge record binds one existing immutable engineering commit and same-name manifest", () => {
  const registry = readJson("tonggan-bridge/BRIDGE-REGISTRY.json");
  for (const entry of registry.records) {
    assert.match(entry.commit_sha, /^[0-9a-f]{40}$/);
    assert.equal(entry.resource, `${path.basename(entry.manifest, ".json")}@${entry.commit_sha}`);
    assert.doesNotThrow(() => execFileSync("/usr/bin/git", ["-C", root, "cat-file", "-e", `${entry.commit_sha}^{commit}`]));
    assert.equal(fs.existsSync(path.join(root, entry.manifest)), true);
    const record = readJson(entry.record_path);
    assert.equal(record.bridge_id, entry.bridge_id);
    assert.deepEqual(record.binding, {
      repo: entry.repo,
      branch: entry.branch,
      commit_sha: entry.commit_sha,
      target: entry.target,
      resource: entry.resource,
      manifest: entry.manifest,
    });
  }
});

test("blocked bridge stores the approved failed-before-mutation workorder without secrets", () => {
  const workorder = readJson("tonggan-bridge/workorders/TGB-20260727-001.json");
  const receipt = readJson("tonggan-bridge/receipts/TGB-20260727-001.json");
  assert.equal(workorder.workorder_id, "56f6ca23-d242-4fab-88f3-81fed692e00d");
  assert.equal(workorder.owner_email_approval, "approved");
  assert.equal(receipt.deployment_result, "FAILED_BEFORE_MUTATION");
  assert.equal(receipt.diagnostic_code, "DEPLOYMENT_SOURCE_COMMIT_NOT_FOUND_IN_CONFIGURED_REPOSITORY");
  assert.equal(receipt.server_runtime_proven, false);
  assert.equal(receipt.public_route_proven, false);
  assert.doesNotMatch(JSON.stringify({ workorder, receipt }), /Bearer |session_token|approval_token|password|private_key/i);
});
