"use strict";
/**
 * Copyright © 2018 Emu Analytics
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handler = exports.builder = exports.desc = exports.command = void 0;
const utils_1 = require("../../utils");
const inquirer = __importStar(require("inquirer"));
const uuid_1 = require("uuid");
exports.command = ['update <email>'];
exports.desc = 'Update a user';
const builder = (args) => {
    return args
        .option('firstName', { description: 'First name', type: 'string' })
        .option('lastName', { description: 'Last name', type: 'string' })
        .option('roles', { alias: 'r', description: 'Roles (comma-separated)', type: 'array' })
        .option('emailVerified', { description: 'Email verified', type: 'boolean' })
        .option('enabled', { alias: 'e', description: 'Login enabled', type: 'boolean' })
        .option('interactive', {
        alias: 'i',
        describe: 'Show interactive prompts',
        type: 'boolean',
        default: 'true'
    })
        .positional('email', { describe: 'Email (or unique prefix)', type: 'string' });
};
exports.builder = builder;
function handler(params) {
    return __awaiter(this, void 0, void 0, function* () {
        const client = params.client;
        const email = params.email;
        try {
            const user = yield (0, utils_1.resolveResource)(email, client.auth.users, 'email');
            if (params.interactive) {
                const answers = yield inquirer.prompt([
                    {
                        type: 'input',
                        name: 'firstName',
                        message: 'First name',
                        default: params.firstName || user.firstName
                    },
                    { type: 'input', name: 'lastName', message: 'Last name', default: params.lastName || user.lastName },
                    {
                        type: 'input',
                        name: 'roles',
                        message: 'Roles (comma separated)',
                        default: (params.roles || user.roles).join(', ')
                    },
                    {
                        type: 'confirm',
                        name: 'emailVerified',
                        message: 'Verified?',
                        default: params.hasOwnProperty('emailVerified') ? params.emailVerified : user.emailVerified
                    },
                    {
                        type: 'confirm',
                        name: 'enabled',
                        message: 'Enabled?',
                        default: params.hasOwnProperty('enabled') ? params.enabled : user.enabled
                    },
                    {
                        type: 'confirm',
                        name: 'changePassword',
                        message: 'Change password?',
                        default: false
                    },
                    {
                        type: 'password',
                        name: 'password',
                        message: 'New password',
                        when: ({ changePassword }) => changePassword
                    },
                    {
                        type: 'password',
                        name: 'confirmPassword',
                        message: 'Confirm password',
                        when: ({ changePassword }) => changePassword
                    }
                ]);
                if (answers.changePassword) {
                    if (answers.password !== answers.confirmPassword) {
                        throw new Error('Passwords do not match');
                    }
                    params.password = answers.password;
                }
                params.firstName = answers.firstName;
                params.lastName = answers.lastName;
                params.roles = answers.roles.split(',').map((r) => r.trim());
                params.emailVerified = answers.emailVerified;
                params.enabled = answers.enabled;
            }
            if (params.password) {
                const passwordResetToken = (0, uuid_1.v4)();
                yield client.auth.users.update(user.id, {
                    passwordResetToken
                });
                yield client.auth.resetPassword(user.email, params.password, user.applicationId, passwordResetToken);
            }
            const updatedUser = yield client.auth.users.update(user.id, {
                firstName: params.firstName,
                lastName: params.lastName,
                roles: params.roles,
                emailVerified: params.emailVerified,
                enabled: params.enabled
            });
            if (params.format === 'table') {
                (0, utils_1.logObject)(updatedUser, 'table');
            }
            else {
                (0, utils_1.logObject)(updatedUser, 'json');
            }
        }
        catch (e) {
            (0, utils_1.logError)(e);
        }
    });
}
exports.handler = handler;
//# sourceMappingURL=update.js.map