import { error } from '../model/error.js';
import { getGlobalModules } from '../model/npm.js';

export const getMetadata = () => ({
    name: 'install',
    desc: 'Install CLI plugin',
    usage: 'afctl install PLUGIN',
    options: {
        plugin: {
            keys: [],
            type: 'string',
            mandatory: true,
            multiple: false,
            helpLiteral: 'PLUGIN',
            helpText: 'CLI plugin package name',
            index: 0
        }
    }
});

export const run = async ({ args, config, cli, console }) => {
    console.debug(`Installing plugin '${args.plugin}'`);
    if (!config.plugins) {
        console.debug('Initializing plugins configuration');
        config.plugins = {};
    }
    console.debug('Looking for globally installed modules');
    const globalModules = await getGlobalModules();
    console.debug(`Found ${globalModules.length} globally installed modules`);
    const pluginKeyword = cli.name.slice(cli.name.indexOf('/') + 1) + '-plugin';
    const pluginModules = globalModules.filter(m => m.pkg.keywords?.includes?.(pluginKeyword));
    const pluginModule = pluginModules.find(m => m.pkg.name === args.plugin);
    const isInstalled = config.plugins[args.plugin];
    if (pluginModules.length) {
        console.debug(
            `Globally installed modules with '${pluginKeyword}' keyword:\n` +
            pluginModules.map(
                m => ` - ${m.pkg.name}` + (config.plugins[m.pkg.name] ? ' (installed)' : '')
            ).join('\n')
        );
    } else {
        console.debug(`No globally installed modules with '${pluginKeyword}' keyword found`);
    }
    if (pluginModule && isInstalled) {
        return [`CLI plugin '${args.plugin}' already installed`];
    }
    if (!pluginModule && isInstalled) {
        // TODO: try to re-install from npm
        throw error(`CLI plugin '${args.plugin}' is installed, but coresponding module is missing`);
    }
    if (pluginModule && !isInstalled) {
        config.plugins[args.plugin] = {
            dir: pluginModule.dir,
            main: pluginModule.pkg.main
        };
        await config.save();
        return [`CLI plugin '${args.plugin}' successfully installed`];
    }
    // TODO: try to install from npm
    throw error(
        `Failed to install CLI plugin '${args.plugin}'. ` +
        'Make sure the corresponing module is globally installed'
    );
};
