import { listApplications } from '../../srv/list-applications.js';
import { listApplicationVersions } from '../../srv/list-application-versions.js';

export const getApplicationOrVersionNamesCompletion =
    ({versionsCompletion}) => async ({console, args, config, fetch}) => {
        const profile = config?.profiles[config?.active_profile];
        const numberOfArgs = args._.length;
        if (numberOfArgs === 3) {
            try {
                const applications = await listApplications({ console, profile, fetch });
                return applications.value.map(app => app.application_name);
            } catch (err) {
                console.debug('Failed to get list of applications for arguments completion: ' + err.message);
                return undefined;
            }
        }
        if (numberOfArgs === 4 && versionsCompletion) {
            const application = args._[2];
            try {
                const versions = await listApplicationVersions({ console, profile, fetch, application });
                return versions.value.map(version => version.version_name);
            } catch (err) {
                console.debug('Failed to get list of application versions for arguments completion: ' + err.message);
                return undefined;
            }
        }
        return undefined;
    };
