"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_test_1 = __importDefault(require("node:test"));
const strict_1 = __importDefault(require("node:assert/strict"));
const index_js_1 = require("../index.js");
function makeStubSession(targetId) {
    const tx = {
        async run(cypher, params = {}) {
            if (cypher.includes("RETURN elementId(t) AS id, labels(t) AS labels")) {
                const ids = params.ids ?? [];
                const records = ids
                    .filter((id) => id === targetId)
                    .map((id) => ({
                    get(field) {
                        if (field === "id")
                            return id;
                        if (field === "labels")
                            return ["Account"];
                        throw new Error(`unknown field ${field}`);
                    },
                }));
                return { records };
            }
            if (cypher.includes("CREATE (n:")) {
                return {
                    records: [
                        {
                            get(field) {
                                if (field === "nodeId")
                                    return "new-element-id";
                                if (field === "nodeLabels")
                                    return ["Conversation"];
                                throw new Error(`unknown field ${field}`);
                            },
                        },
                    ],
                };
            }
            if (cypher.includes("CREATE (a)-[") || cypher.includes("CREATE (b)-[")) {
                return {
                    records: [],
                    summary: {
                        counters: {
                            updates: () => ({ relationshipsCreated: 1 }),
                        },
                    },
                };
            }
            return { records: [] };
        },
    };
    return {
        async executeWrite(work) {
            return await work(tx);
        },
    };
}
const VALID_UUID = "12345678-9abc-def0-1234-56789abcdef0";
const TARGET_ID = "target-element-id";
const REL = [
    { type: "PART_OF", direction: "outgoing", targetNodeId: TARGET_ID },
];
function captureStderr() {
    const original = process.stderr.write.bind(process.stderr);
    let buf = "";
    process.stderr.write =
        (chunk) => {
            buf += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString();
            return true;
        };
    return {
        restore: () => {
            process.stderr.write = original;
        },
        output: () => buf,
    };
}
(0, node_test_1.default)("rejects null accountId from non-system writer", async () => {
    const cap = captureStderr();
    try {
        await strict_1.default.rejects(() => (0, index_js_1.writeNodeWithEdges)({
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            session: makeStubSession(TARGET_ID),
            labels: ["Conversation"],
            props: { accountId: null },
            relationships: REL,
            createdBy: { agent: "test-agent", session: "s" },
            expectedAccountId: VALID_UUID,
        }), /invalid-account-id/);
        cap.restore();
        strict_1.default.match(cap.output(), /\[graph-write\] reject reason=invalid-account-id accountId=missing writer=test-agent\b/);
    }
    finally {
        cap.restore();
    }
});
(0, node_test_1.default)("rejects non-UUID accountId from non-system writer", async () => {
    const cap = captureStderr();
    try {
        await strict_1.default.rejects(() => (0, index_js_1.writeNodeWithEdges)({
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            session: makeStubSession(TARGET_ID),
            labels: ["Conversation"],
            props: { accountId: "evil-leak" },
            relationships: REL,
            createdBy: { agent: "test-agent", session: "s" },
            expectedAccountId: VALID_UUID,
        }), /invalid-account-id/);
        cap.restore();
        strict_1.default.match(cap.output(), /\[graph-write\] reject reason=invalid-account-id accountId=evil-lea writer=test-agent\b/);
    }
    finally {
        cap.restore();
    }
});
(0, node_test_1.default)("rejects UUID-shape accountId that does not match the expected one", async () => {
    const stranger = "ffffffff-1111-2222-3333-444444444444";
    const cap = captureStderr();
    try {
        await strict_1.default.rejects(() => (0, index_js_1.writeNodeWithEdges)({
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            session: makeStubSession(TARGET_ID),
            labels: ["Conversation"],
            props: { accountId: stranger },
            relationships: REL,
            createdBy: { agent: "test-agent", session: "s" },
            expectedAccountId: VALID_UUID,
        }), /invalid-account-id/);
        cap.restore();
        strict_1.default.match(cap.output(), /\[graph-write\] reject reason=invalid-account-id accountId=ffffffff writer=test-agent\b/);
    }
    finally {
        cap.restore();
    }
});
(0, node_test_1.default)("accepts matching accountId from non-system writer", async () => {
    const result = await (0, index_js_1.writeNodeWithEdges)({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        session: makeStubSession(TARGET_ID),
        labels: ["Conversation"],
        props: { accountId: VALID_UUID },
        relationships: REL,
        createdBy: { agent: "test-agent", session: "s" },
        expectedAccountId: VALID_UUID,
    });
    strict_1.default.equal(result.nodeId, "new-element-id");
    strict_1.default.equal(result.edgesCreated, 1);
});
(0, node_test_1.default)("system bootstrap exemption: bad accountId still proceeds", async () => {
    const result = await (0, index_js_1.writeNodeWithEdges)({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        session: makeStubSession(TARGET_ID),
        labels: ["Conversation"],
        // accountId is intentionally wrong; system bootstrap exempts it.
        props: { accountId: "not-a-uuid" },
        relationships: REL,
        createdBy: { agent: "system", source: "writeAdminUserAndPerson" },
        expectedAccountId: VALID_UUID,
    });
    strict_1.default.equal(result.nodeId, "new-element-id");
});
//# sourceMappingURL=account-id-gate.test.js.map