/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils/internal";
import { withSchemaValidation, } from "../codec/index.js";
import { JsonCompatibleReadOnlySchema, } from "../util/index.js";
import { EncodedEditManager } from "./editManagerFormatV5.js";
import { decodeSharedBranch, encodeSharedBranch } from "./editManagerCodecsCommons.js";
export function makeV5CodecWithVersion(changeCodec, revisionTagCodec, options, version) {
    const format = EncodedEditManager(changeCodec.json.encodedSchema ?? JsonCompatibleReadOnlySchema);
    const codec = withSchemaValidation(format, {
        encode: (data, context) => {
            const mainBranch = encodeSharedBranch(changeCodec, revisionTagCodec, data.main, context, data.originator);
            assert(data.originator !== undefined, 0xc65 /* Cannot encode V5 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;
        },
    }, options.jsonValidator);
    // TODO: makeVersionedValidatedCodec and withSchemaValidation should allow the codec to decode JsonCompatibleReadOnly, or Versioned or something like that,
    // and not leak the internal encoded format in the API surface.
    // Fixing that would remove the need for this cast.
    return codec;
}
//# sourceMappingURL=editManagerCodecsV5.js.map