"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_loggers_1 = require("@pnpm/core-loggers");
const types_1 = require("@pnpm/types");
async function save(prefix, packageManifest, packageSpecs, opts) {
    packageSpecs.forEach((packageSpec) => {
        if (packageSpec.saveType) {
            const spec = packageSpec.pref || findSpec(packageSpec.name, packageManifest);
            if (spec) {
                packageManifest[packageSpec.saveType] = packageManifest[packageSpec.saveType] || {};
                packageManifest[packageSpec.saveType][packageSpec.name] = spec;
                types_1.DEPENDENCIES_FIELDS.filter((depField) => depField !== packageSpec.saveType).forEach((deptype) => {
                    if (packageManifest[deptype]) {
                        delete packageManifest[deptype][packageSpec.name];
                    }
                });
                if (packageSpec.peer === true) {
                    packageManifest.peerDependencies = packageManifest.peerDependencies || {};
                    packageManifest.peerDependencies[packageSpec.name] = spec;
                }
            }
        }
        else if (packageSpec.pref) {
            const usedDepType = guessDependencyType(packageSpec.name, packageManifest) || 'dependencies';
            packageManifest[usedDepType] = packageManifest[usedDepType] || {};
            packageManifest[usedDepType][packageSpec.name] = packageSpec.pref;
        }
    });
    core_loggers_1.packageManifestLogger.debug({
        prefix,
        updated: packageManifest,
    });
    return packageManifest;
}
exports.default = save;
function findSpec(depName, manifest) {
    const foundDepType = guessDependencyType(depName, manifest);
    return foundDepType && manifest[foundDepType][depName];
}
function guessDependencyType(depName, manifest) {
    return types_1.DEPENDENCIES_FIELDS
        .find((depField) => Boolean(manifest[depField] && manifest[depField][depName]));
}
exports.guessDependencyType = guessDependencyType;
