import { setApplicationVersionLogLevel } from '../srv/set-application-version-log-level.js';
import { getApplication } from '../srv/get-application.js';
import { getApplicationVersion } from '../srv/get-application-version.js';
import { getApplicationOrVersionNamesCompletion } from './common/completions.js';

export const getMetadata = () => ({
    name: 'set-log-level',
    desc: 'Set log level for application version',
    alias: 'sll',
    usage: 'afctl set-log-level APPLICATION [VERSION] --debug|--error',
    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 (defaults to active version)',
            index: 1
        },
        debug: {
            keys: ['--debug'],
            type: 'boolean',
            mandatory: false,
            multiple: false,
            helpText: 'Set log level to debug'
        },
        error: {
            keys: ['--error'],
            type: 'boolean',
            mandatory: false,
            multiple: false,
            helpText: 'Set log level to error'
        }
    }
});

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

export const run = async ({ args, config, console, fetch }) => {
    const profile = config?.profiles?.[config?.active_profile];

    // Validate that exactly one log level flag is provided
    const debugFlag = args.debug;
    const errorFlag = args.error;

    if (!debugFlag && !errorFlag) {
        throw new Error('You must specify either --debug or --error flag');
    }

    if (debugFlag && errorFlag) {
        throw new Error('You cannot specify both --debug and --error flags');
    }

    const logLevel = debugFlag ? 'debug' : 'error';

    let version = args.version;

    if (!version) {
        // Get active version, if not provided explicitly
        console.debug(
            `Application '${args.application}' version was not provided explicitly. ` +
            'Getting the current active version.'
        );

        const applicationMetadata = await getApplication({
            console, profile, fetch,
            application: args.application
        });

        version = applicationMetadata?.active_version_name;

        if (!version) {
            throw new Error(`No active version found for application '${args.application}'`);
        }

        console.debug(`Using active version '${version}'`);
    }

    console.debug(`Setting log level '${logLevel}' for application '${args.application}' version '${version}'`);

    await setApplicationVersionLogLevel({
        console,
        profile,
        fetch,
        application: args.application,
        version,
        logLevel
    });

    // Get the version details to check for TTL
    const versionDetails = await getApplicationVersion({
        console,
        profile,
        fetch,
        application: args.application,
        version
    });

    const ttl = versionDetails?.log_level_ttl_seconds;
    let message = `Log level ${logLevel} for ${args.application} ${version} configured successfully`;

    // Add expiration information if TTL is set (not -1 and not undefined/null)
    if (ttl !== undefined && ttl !== null && ttl !== -1) {
        const expirationDate = new Date(Date.now() + (ttl * 1000));
        message += ` (expires at ${expirationDate.toISOString()})`;
    }

    return message;
};
