"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, packageJson, packageSpecs, opts) {
    packageSpecs.forEach((packageSpec) => {
        if (packageSpec.saveType) {
            const spec = packageSpec.pref || findSpec(packageSpec.name, packageJson);
            if (spec) {
                packageJson[packageSpec.saveType] = packageJson[packageSpec.saveType] || {};
                packageJson[packageSpec.saveType][packageSpec.name] = spec;
                types_1.DEPENDENCIES_FIELDS.filter((depField) => depField !== packageSpec.saveType).forEach((deptype) => {
                    if (packageJson[deptype]) {
                        delete packageJson[deptype][packageSpec.name];
                    }
                });
                if (packageSpec.peer === true) {
                    packageJson.peerDependencies = packageJson.peerDependencies || {};
                    packageJson.peerDependencies[packageSpec.name] = spec;
                }
            }
        }
        else if (packageSpec.pref) {
            const usedDepType = guessDependencyType(packageSpec.name, packageJson) || 'dependencies';
            packageJson[usedDepType] = packageJson[usedDepType] || {};
            packageJson[usedDepType][packageSpec.name] = packageSpec.pref;
        }
    });
    core_loggers_1.packageJsonLogger.debug({
        prefix,
        updated: packageJson,
    });
    return packageJson;
}
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;
