import { updateApplicationProperty } from '../srv/update-application-property.js';
import { getApplicationOrVersionNamesCompletion } from './common/completions.js';

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

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

export const run = async ({ args, config, console, prompt, fetch }) => {
    if (!args.force) {
        console.debug('Prompting to get user approval for stop');
        const answer = await prompt({
            message: `Are you sure you want to stop application ${args.application} (y/n)`,
            default: 'n'
        });
        if (!['y', 'yes'].includes(answer)) {
            console.debug('Stop application rejected');
            return;
        }
        console.debug('Stop application approved');
    }
    const profile = config?.profiles?.[config?.active_profile];
    console.debug(`Stopping application '${args.application}'`);
    await updateApplicationProperty({
        console, profile, fetch,
        application: args.application,
        property: {
            name: 'state',
            value: 'stopped'
        }
    });
};
