import { getApplication } from '../../srv/get-application.js';

/**
 * Resolves the application version, either from the provided argument or by fetching the active version
 * @param {Object} params - Parameters object
 * @param {string} params.application - Application name
 * @param {string|undefined} params.version - Version name (optional)
 * @param {Object} params.console - Console logger
 * @param {Object} params.profile - User profile
 * @param {Function} params.fetch - Fetch function
 * @returns {Promise<string>} Resolved version name
 */
export const resolveApplicationVersion = async ({ application, version, console, profile, fetch }) => {
    if (version) {
        return version;
    }

    // Get active version, if not provided explicitly
    console.debug(
        `Application '${application}' version was not provided explicitly. ` +
        'Getting application metadata to resolve version.'
    );
    const applicationMetadata = await getApplication({
        console, profile, fetch,
        application
    });
    const resolvedVersion = applicationMetadata?.active_version_name;
    console.debug(`Using version '${resolvedVersion}'`);

    return resolvedVersion;
};
