import { deleteApplication } from '../srv/delete-application.js';
import { deleteApplicationVersion } from '../srv/delete-application-version.js';
import { getApplicationOrVersionNamesCompletion } from './common/completions.js';

export const getMetadata = () => ({
    name: 'delete',
    desc: 'Delete deployed application or application version',
    alias: 'd',
    usage: 'afctl delete APPLICATION [VERSION] [-f]',
    options: {
        application: {
            keys: [],
            type: 'string',
            mandatory: true,
            multiple: false,
            helpLiteral: 'APPLICATION',
            helpText: 'Name of the deployed application',
            index: 0
        },
        version: {
            keys: [],
            type: 'string',
            mandatory: false,
            multiple: false,
            helpLiteral: 'VERSION',
            helpText: 'Name of the application version',
            index: 1
        },
        force: {
            keys: ['--force','-f'],
            type: 'boolean',
            mandatory: false,
            multiple: false,
            helpLiteral: '',
            helpText: 'Force deletion without prompt',
            index: 2
        }
    }
});

export const getCompletion = getApplicationOrVersionNamesCompletion({versionCompletion: true});

export const run = async ({ args, config, console, fetch, prompt }) => {
    if (!args.force) {
        console.debug('Prompting to get user approval for deletion');
        const answer = await prompt({
            message: `Are you sure you want to delete ${args.application} (y/n)`,
            default: 'n'
        });
        if (!['y', 'yes'].includes(answer)) {
            console.debug('Deletion rejected');
            return;
        }
        console.debug('Deletion approved');
    }
    const profile = config?.profiles?.[config?.active_profile];
    if (args.version) {
        await deleteApplicationVersion({
            console, profile, fetch, application: args.application, version: args.version });
    } else {
        await deleteApplication(
            { console, profile, fetch, application: args.application });
    }
};
