import { Command, flags } from '@heroku-cli/command';
import { color, hux } from '@heroku/heroku-cli-util';
import { ux } from '@oclif/core/ux';
export default class Drains extends Command {
    static description = 'display the log drains of an app';
    static flags = {
        app: flags.app({ required: true }),
        extended: flags.boolean({ char: 'x', hidden: true }),
        json: flags.boolean({ description: 'output in json format' }),
        remote: flags.remote(),
    };
    async run() {
        const { flags } = await this.parse(Drains);
        let path = `/apps/${flags.app}/log-drains`;
        if (flags.extended) {
            path += '?extended=true';
        }
        const { body: drains } = await this.heroku.get(path);
        if (flags.json) {
            hux.styledJSON(drains);
        }
        else {
            const [drainsWithAddons, drainsWithoutAddons] = drains.reduce((acc, drain) => {
                if (drain.addon) {
                    acc[0].push(drain);
                }
                else {
                    acc[1].push(drain);
                }
                return acc;
            }, [[], []]);
            if (drainsWithoutAddons.length > 0) {
                hux.styledHeader('Drains');
                drainsWithoutAddons.forEach((drain) => {
                    styledDrain(drain.url || '', color.name(drain.token || ''), drain);
                });
            }
            if (drainsWithAddons.length > 0) {
                const addons = await Promise.all(drainsWithAddons.map((d) => this.heroku.get(`/apps/${flags.app}/addons/${d.addon?.name}`)));
                hux.styledHeader('Add-on Drains');
                addons.forEach(({ body: addon }, i) => {
                    styledDrain(color.addon(addon.plan?.name || ''), color.addon(addon.name || ''), drainsWithAddons[i]);
                });
            }
        }
    }
}
function styledDrain(id, name, drain) {
    let output = `${id} (${name})`;
    if (drain.extended)
        output += ` drain_id=${drain.extended.drain_id}`;
    ux.stdout(output);
}
