"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const js_yaml_1 = require("js-yaml");
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const cli_table3_1 = __importDefault(require("cli-table3"));
const moment = require("moment");
const util_1 = require("../../commandUtil/util");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const constants_1 = require("@mablhq-internal/runtime/core/constants");
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
const list_1 = require("../../commandUtil/list");
exports.command = 'list';
exports.describe = 'List users from a workspace';
exports.builder = (0, list_1.getListBuilderOptions)('users');
exports.handler = (0, cliUtil_1.failWrapper)(listUsers);
async function listUsers(parsed) {
    const output = parsed.output;
    const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
    const limit = parsed.limit;
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const users = await apiClient.getUsers(workspaceId, limit);
    printUsers(users, output, workspaceId);
    return users.length;
}
function printUsers(users, outputFormat, workspaceId) {
    switch (outputFormat) {
        case 'json':
            loggingProvider_1.logger.info(JSON.stringify(users, null, 2));
            break;
        case 'yaml':
            loggingProvider_1.logger.info((0, js_yaml_1.dump)(users));
            break;
        default:
            const table = new cli_table3_1.default({
                head: ['ID', 'Name', 'Role', 'Email', 'Created time'],
                wordWrap: true,
            });
            users.forEach((user) => {
                const userRole = user.roles?.find((role) => role.organization_id === workspaceId)
                    ?.role ?? 'unknown';
                table.push([
                    { rowSpan: 1, content: user.id, vAlign: 'center' },
                    { rowSpan: 1, content: user.name, vAlign: 'center' },
                    { rowSpan: 1, content: userRole, vAlign: 'center' },
                    { rowSpan: 1, content: user.email, vAlign: 'center' },
                    {
                        rowSpan: 1,
                        content: moment.utc(user.created_time).format(constants_1.ListTimeFormat),
                        vAlign: 'center',
                    },
                ]);
            });
            loggingProvider_1.logger.info(table.toString());
            break;
    }
}
