import { Command, flags } from '@heroku-cli/command';
import { HerokuAPIError } from '@heroku-cli/command/lib/api-client.js';
import { color, hux } from '@heroku/heroku-cli-util';
import { ux } from '@oclif/core/ux';
import { lazyModuleLoader } from '../../lib/lazy-module-loader.js';
import { getOwner, isTeamApp } from '../../lib/teamUtils.js';
export default class AccessIndex extends Command {
    static description = 'list who has access to an app';
    static flags = {
        app: flags.app({ required: true }),
        json: flags.boolean({ description: 'output in json format' }),
        remote: flags.remote({ char: 'r' }),
    };
    static topic = 'access';
    async run() {
        const _ = await lazyModuleLoader.loadLodash();
        const { flags } = await this.parse(AccessIndex);
        const { app: appName, json } = flags;
        const { body: app } = await this.heroku.get(`/apps/${appName}`);
        let { body: collaborators } = await this.heroku.get(`/apps/${appName}/collaborators`);
        if (isTeamApp(app.owner?.email)) {
            const teamName = getOwner(app.owner?.email);
            try {
                const { body: members } = await this.heroku.get(`/teams/${teamName}/members`);
                let admins = members.filter(member => member.role === 'admin');
                const { body: adminPermissions } = await this.heroku.get('/teams/permissions');
                admins = _.forEach(admins, admin => {
                    admin.user = { email: admin.email };
                    admin.permissions = adminPermissions;
                    return admin;
                });
                collaborators = buildCollaboratorsArray(collaborators, admins, _);
            }
            catch (error) {
                if (!(error instanceof HerokuAPIError && error.http.statusCode === 403))
                    throw error;
            }
        }
        if (json)
            printJSON(collaborators);
        else
            printAccess(app, collaborators, _);
    }
}
function buildCollaboratorsArray(collaboratorsRaw, admins, _) {
    const collaboratorsNoAdmins = _.reject(collaboratorsRaw, { role: 'admin' });
    return _.union(collaboratorsNoAdmins, admins);
}
function buildTableColumns(showPermissions) {
    const baseColumns = {
        email: {
            get: ({ email }) => color.user(email),
        },
        role: {
            get: ({ role }) => color.info(role),
        },
    };
    if (showPermissions) {
        return {
            ...baseColumns,
            permissions: {},
        };
    }
    return baseColumns;
}
function printAccess(app, collaborators, _) {
    const showPermissions = isTeamApp(app.owner?.email);
    collaborators = _.chain(collaborators)
        .sortBy((c) => c.email || c.user.email)
        .reject((c) => /herokumanager\.com$/.test(c.user.email))
        .map((collab) => {
        const { email } = collab.user;
        const { permissions, role } = collab;
        const data = { email, role: role || 'collaborator' };
        if (showPermissions) {
            data.permissions = _.map(_.sortBy(permissions, 'name'), 'name').join(', ');
        }
        return data;
    })
        .value();
    const tableColumns = buildTableColumns(showPermissions);
    hux.table(collaborators, tableColumns);
}
function printJSON(collaborators) {
    ux.stdout(JSON.stringify(collaborators, null, 2));
}
