import { getApplication } from '../srv/get-application.js';
import { listApplications } from '../srv/list-applications.js';
import { listApplicationVersions } from '../srv/list-application-versions.js';
import { getApplicationVersion } from '../srv/get-application-version.js';
import { getApplicationOrVersionNamesCompletion } from './common/completions.js';
import { dimmed, entity } from '../output/style.js';
import { table } from '../output/table.js';
import { toTimeString } from '../output/time.js';

export const getMetadata = () => ({
    name: 'list',
    desc: 'List deployed applications or application versions or application version details',
    usage: 'afctl list [APPLICATION [VERSION]]',
    options: {
        application: {
            keys: [],
            type: 'string',
            mandatory: false,
            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 deployed application version',
            index: 1
        }
    }
});

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

export const run = async ({ args, config, console, fetch }) => {
    const profile = config?.profiles?.[config?.active_profile];
    // list application version details
    if (args.application && args.version) {
        const version = await getApplicationVersion({
            console, profile, fetch,
            application: args.application,
            version: args.version
        });
        return [
            entity('Version\n'),
            table({
                type: 'columns',
                headers: [
                    { name: 'application_name', title: 'Application' },
                    { name: 'version_name', title: 'Version' },
                    { name: 'created', title: 'Created' },
                    { name: 'updated', title: 'Updated' },
                    { name: 'log_level', title: 'Log level' },
                    { name: 'log_ttl', title: 'Log level expiration' }
                ],
                data: [{
                    application_name: version.application_name,
                    version_name: version.version_name,
                    created: version.created,
                    updated: version.updated,
                    log_level: version.log_level,
                    log_ttl: version.log_level_ttl_seconds === -1
                        ? dimmed('-')
                        : toTimeString(Date.now() + version.log_level_ttl_seconds * 1000)
                }]
            })
        ];
    }
    // list application versions
    if (args.application) {
        const application = await getApplication({ console, profile, fetch, application: args.application });
        const versions = await listApplicationVersions({ console, profile, fetch, application: args.application });
        return [
            entity('Application\n'),
            table({
                type: 'columns',
                headers: [
                    { name: 'application_name', title: 'Name'},
                    { name: 'version_name', title: 'Active Version'},
                    { name: 'application_state', title: 'State'},
                    { name: 'business_solution', title: 'Business Solution'},
                    { name: 'application_url', title: 'URL'}
                ],
                data: [{
                    application_name: application.application_name,
                    version_name: application.active_version_name,
                    application_state: application.state === 'stopped'
                        ? dimmed(application.state)
                        : application.state,
                    business_solution: application.business_solution || dimmed('-'),
                    application_url: application.application_urls?.[0]
                }]
            }),
            entity('\nVersions\n'),
            table({
                type: 'rows',
                headers: [
                    { name: 'version_name', title: 'Version'},
                    { name: 'log_level', title: 'Log-Level'},
                    { name: 'url', title: 'URL'},
                ],
                data: versions?.value?.map?.(version => ({
                    version_name: version.version_name,
                    log_level: version.log_level || 'error',
                    url: version.urls[0]
                })) || []
            })
        ];
    }
    // list applications
    const applications = await listApplications({ console, profile, fetch });
    return [
        entity('Applications\n'),
        table({
            type: 'rows',
            headers: [
                { name: 'application_name', title: 'Name'},
                { name: 'version_name', title: 'Version'},
                { name: 'application_state', title: 'State'},
                { name: 'application_url', title: 'URL'},
            ],
            data: applications?.value?.map?.(application => {
                const style = application.state === 'stopped' ? dimmed : t => t;
                return {
                    application_name: style(application.application_name),
                    version_name: style(application.active_version_name),
                    application_state: style(application.state),
                    application_url: style(application.application_urls?.[0])
                };
            }) || []
        })
    ];
};
