"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.xAdd = void 0;
const json_pointer_1 = require("@jsonjoy.com/json-pointer");
const util_1 = require("./util");
const json_1 = require("../../json-patch/codec/json");
const xAdd = (add, op) => {
    if ((0, json_pointer_1.isRoot)(add.path))
        return null;
    if ((0, json_pointer_1.isRoot)(op.path))
        return op;
    const lastIndex = add.path.length - 1;
    const lastStep = add.path[lastIndex];
    const isLastStepNumberLike = (0, json_pointer_1.isValidIndex)(lastStep);
    if ((0, json_pointer_1.isChild)(add.path, op.path) && !isLastStepNumberLike)
        return null;
    if (isLastStepNumberLike) {
        const newPath = (0, util_1.bumpArrayPath)(add.path, op.path);
        const newFrom = op.from ? (0, util_1.bumpArrayPath)(add.path, op.from) : undefined;
        if (newPath || newFrom) {
            const operation = {
                ...op.toJson(),
                path: newPath ? (0, json_pointer_1.formatJsonPointer)(newPath) : op.path,
            };
            if (newFrom)
                operation.from = (0, json_pointer_1.formatJsonPointer)(newFrom);
            // TODO: The second argument should not be {}
            return (0, json_1.operationToOp)(operation, {});
        }
    }
    return op;
};
exports.xAdd = xAdd;
//# sourceMappingURL=xAdd.js.map