import { dimmed } from '../output/style.js';
import { logout } from '../srv/logout.js';

export const getMetadata = () => ({
    name: 'logout',
    desc: 'Logout from authorization server and remove locally cached user data',
    usage: 'afctl logout [PROFILE]',
    options: {
        profile: {
            keys: [],
            type: 'string',
            mandatory: false,
            multiple: false,
            helpLiteral: 'PROFILE',
            helpText: 'Name of the configuration profile',
            index: 0
        }
    }
});

export const getCompletion = ({args, config}) => {
    if (args._.length === 3) {
        return Object.keys(config.profiles).map(
            profile => `${profile}:${config.profiles[profile].server_url}`
        );
    }
    return undefined;
};

export const run = async ({ console, cli, config, args, fetch }) => {
    let profileName = config.active_profile;

    // Profile argument provided
    if (args.profile && (args.profile !== config.active_profile)) {
        profileName = args.profile;
    }

    console.debug(`Deleting user data from profile '${profileName}'`);
    const profile = config.profiles[profileName];

    // Check profile exists
    if (!profile) {
        const err = new Error(
            `Profile with name '${profileName}' does not exist.\n` +
            `To see list of available profiles run '${dimmed(cli.bin + ' config')}'`
        );
        throw err;
    }

    // Logout from authorization server
    await logout({ console, config, fetch });

    if (profile.token) {
        delete profile.token;
    }
    if (profile.key) {
        delete profile.key;
    }
    if (profile.cert) {
        delete profile.cert;
    }
    await config.save();
};
