"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRollbackUpdate = getRollbackUpdate;
const logger_1 = require("../../../../logger");
function getRollbackUpdate(config, versions, version) {
    const { packageFile, versioning, depName, currentValue } = config;
    // istanbul ignore if
    if (!('isLessThanRange' in version)) {
        logger_1.logger.debug({ versioning }, 'Current versioning does not support isLessThanRange()');
        return null;
    }
    const lessThanVersions = versions.filter((v) => {
        try {
            return version.isLessThanRange(v.version, currentValue);
        }
        catch (err) /* istanbul ignore next */ {
            return false;
        }
    });
    // istanbul ignore if
    if (!lessThanVersions.length) {
        logger_1.logger.debug({ packageFile, depName, currentValue }, 'Missing version has nothing to roll back to');
        return null;
    }
    logger_1.logger.debug({ packageFile, depName, currentValue }, `Current version not found - rolling back`);
    logger_1.logger.debug({ dependency: depName, versions }, 'Versions found before rolling back');
    lessThanVersions.sort((a, b) => version.sortVersions(a.version, b.version));
    let newRelease;
    if (currentValue && version.isStable(currentValue)) {
        newRelease = lessThanVersions
            .filter((v) => version.isStable(v.version))
            .pop();
    }
    let newVersion = newRelease?.version;
    let registryUrl = newRelease?.registryUrl;
    if (!newVersion) {
        newRelease = lessThanVersions.pop();
        newVersion = newRelease?.version;
        registryUrl = newRelease?.registryUrl;
    }
    // istanbul ignore if
    if (!newVersion) {
        logger_1.logger.debug('No newVersion to roll back to');
        return null;
    }
    const newValue = version.getNewValue({
        // TODO #22198
        currentValue: currentValue,
        rangeStrategy: 'replace',
        newVersion,
    });
    return {
        bucket: 'rollback',
        // TODO #22198
        newMajor: version.getMajor(newVersion),
        newValue: newValue,
        newVersion,
        registryUrl,
        updateType: 'rollback',
    };
}
//# sourceMappingURL=rollback.js.map