import { Command, flags } from '@heroku-cli/command';
import { color, hux } from '@heroku/heroku-cli-util';
import { ux } from '@oclif/core/ux';
export default class LabsIndex extends Command {
    static description = 'list experimental features';
    static flags = {
        app: flags.app({ required: false }),
        json: flags.boolean({ description: 'display as json', required: false }),
        remote: flags.remote(),
    };
    static topic = 'labs';
    async run() {
        const { flags } = await this.parse(LabsIndex);
        const [currentUserResponse, userResponse, appResponse] = await Promise.all([
            this.heroku.get('/account'),
            this.heroku.get('/account/features'),
            (flags.app ? this.heroku.get(`/apps/${flags.app}/features`) : null),
        ]);
        let app = null;
        const currentUser = currentUserResponse.body;
        const user = userResponse.body;
        const features = {
            currentUser,
            user,
        };
        // makes sure app isn't added to json object if null
        // eslint-disable-next-line unicorn/no-negated-condition, no-negated-condition
        if (appResponse !== null) {
            app = appResponse?.body;
            features.app = app;
        }
        else {
            features.app = app;
        }
        // general features are managed via `features` not `labs`
        features.user = features.user.filter((f) => f.state !== 'general');
        if (features.app)
            features.app = features.app.filter((f) => f.state !== 'general');
        if (flags.json) {
            printJSON({ app, user });
        }
        else {
            hux.styledHeader(`User Features ${color.user(features.currentUser.email)}`);
            printFeatures(features.user);
            if (features.app) {
                ux.stdout();
                hux.styledHeader(`App Features ${color.app(flags.app)}`);
                printFeatures(features.app);
            }
        }
    }
}
function printFeatures(features) {
    const groupedFeatures = features.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
    const longest = Math.max(...groupedFeatures.map((f) => (f.name || '').length));
    for (const f of groupedFeatures) {
        let line = `${f.enabled ? '[+]' : '[ ]'} ${f.name?.padEnd(longest) ?? ''}`;
        if (f.enabled)
            line = color.success(line);
        line = `${line}  ${f.description}`;
        ux.stdout(line);
    }
}
function printJSON(features) {
    ux.stdout(JSON.stringify(features, null, 2));
}
