/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils/internal";
import { JsonCompatibleReadOnlySchema, } from "../util/index.js";
import { decodeSharedBranch, encodeSharedBranch } from "./editManagerCodecsCommons.js";
import { EncodedEditManager } from "./editManagerFormatVSharedBranches.js";
export function makeSharedBranchesCodecWithVersion(changeCodec, revisionTagCodec, version) {
    const schema = EncodedEditManager(changeCodec.encodedSchema ?? JsonCompatibleReadOnlySchema);
    const codec = {
        schema,
        encode: (data, context) => {
            const mainBranch = encodeSharedBranch(changeCodec, revisionTagCodec, data.main, context, data.originator);
            assert(data.originator !== undefined, 0xca5 /* Cannot encode vSharedBranches summary without originator */);
            const json = {
                main: mainBranch,
                originator: data.originator,
                version,
            };
            if (data.branches !== undefined && data.branches.size > 0) {
                const branches = [];
                for (const [_, branch] of data.branches) {
                    branches.push(encodeSharedBranch(changeCodec, revisionTagCodec, branch, context, data.originator));
                }
                json.branches = branches;
            }
            return json;
        },
        decode: (json, context) => {
            const mainBranch = decodeSharedBranch(changeCodec, revisionTagCodec, json.main, context, json.originator);
            const decoded = {
                main: mainBranch,
                originator: json.originator,
            };
            if (json.branches !== undefined) {
                const branches = new Map();
                for (const branch of json.branches) {
                    const decodedBranch = decodeSharedBranch(changeCodec, revisionTagCodec, branch, context, json.originator);
                    assert(decodedBranch.id !== undefined, 0xc66 /* Shared branches must have an id */);
                    assert(!branches.has(decodedBranch.id), 0xc67 /* Duplicate shared branch id */);
                    branches.set(decodedBranch.id, decodedBranch);
                }
                decoded.branches = branches;
            }
            return decoded;
        },
    };
    return codec;
}
//# sourceMappingURL=editManagerCodecsVSharedBranches.js.map