/* jscpd:ignore-start */
import { SfCommand, Flags, requiredOrgFlagWithDeprecations } from '@salesforce/sf-plugins-core';
import { Messages } from '@salesforce/core';
import c from 'chalk';
import sortArray from 'sort-array';
import { isCI, uxLog, uxLogTable } from '../../../../common/utils/index.js';
import { prompts } from '../../../../common/utils/prompts.js';
import { bulkQuery, bulkUpdate, soqlQuery } from '../../../../common/utils/apiUtils.js';
import { promptProfiles } from '../../../../common/utils/orgUtils.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('sfdx-hardis', 'org');
export default class OrgUserActiveInvalid extends SfCommand {
    static title = 'Reactivate sandbox invalid users';
    static description = `Update sandbox users so their email is valid

  Example: replaces \`toto@company.com.dev.invalid\` with \`toto@company.com.dev.invalid\`

See article below

[![Reactivate all the sandbox users with .invalid emails in 3 clicks](https://github.com/hardisgroupcom/sfdx-hardis/raw/main/docs/assets/images/article-invalid-email.jpg)](https://nicolas.vuillamy.fr/reactivate-all-the-sandbox-users-with-invalid-emails-in-3-clicks-2265af4e3a3d)
`;
    static examples = [
        `$ sf hardis:org:user:activateinvalid`,
        `$ sf hardis:org:user:activateinvalid --target-org my-user@myorg.com`,
        `$ sf hardis:org:user:activateinvalid --profiles 'System Administrator,MyCustomProfile' --target-org my-user@myorg.com`,
    ];
    // public static args = [{name: 'file'}];
    static flags = {
        profiles: Flags.string({
            char: 'p',
            description: 'Comma-separated list of profiles names that you want to reactive users assigned to and with a .invalid email',
        }),
        debug: Flags.boolean({
            char: 'd',
            default: false,
            description: messages.getMessage('debugMode'),
        }),
        websocket: Flags.string({
            description: messages.getMessage('websocket'),
        }),
        skipauth: Flags.boolean({
            description: 'Skip authentication check when a default username is required',
        }),
        'target-org': requiredOrgFlagWithDeprecations,
    };
    // Set this to true if your command requires a project workspace; 'requiresProject' is false by default
    static requiresProject = false;
    profiles = [];
    maxUsersDisplay = 100;
    debugMode = false;
    /* jscpd:ignore-end */
    async run() {
        const { flags } = await this.parse(OrgUserActiveInvalid);
        this.profiles = flags.profiles ? flags.profiles.split(',') : [];
        const hasProfileConstraint = this.profiles !== null && this.profiles.length > 0;
        this.debugMode = flags.debug || false;
        const conn = flags['target-org'].getConnection();
        // Query users that we want to freeze
        uxLog("action", this, c.cyan(`Querying User records with email ending with .invalid...`));
        let userQuery = `SELECT Id,Name,Username,Email,ProfileId FROM User WHERE Email LIKE '%.invalid' and IsActive=true`;
        if (hasProfileConstraint) {
            const profilesQuery = `SELECT Id FROM Profile WHERE Name IN ('${this.profiles.join("','")}')`;
            const profilesQueryRes = await soqlQuery(profilesQuery, conn);
            const profileIds = profilesQueryRes.records.map((profile) => profile.Id);
            userQuery += ` and ProfileId IN ('${profileIds.join("','")}')`;
        }
        const userQueryRes = await bulkQuery(userQuery, conn);
        const usersToActivate = userQueryRes.records;
        // Check empty result
        if (usersToActivate.length === 0) {
            const outputString = `No matching user records found with email ending with .invalid`;
            uxLog("warning", this, c.yellow(outputString));
            return { outputString };
        }
        let usersToActivateFinal = [...usersToActivate];
        // Request confirmation or selection from user
        if (!isCI && !hasProfileConstraint) {
            const confirmSelect = await prompts({
                type: 'select',
                name: 'value',
                initial: true,
                message: c.cyanBright(`Do you want to replace invalid mails by valid mails for all ${c.bold(usersToActivate.length)} found users in org ${c.green(flags['target-org'].getUsername())} ?`),
                description: 'Choose whether to update email addresses for all found users or select specific ones',
                placeholder: 'Select an option',
                choices: [
                    { title: `Yes, all ${c.bold(usersToActivate.length)} users`, value: 'all' },
                    { title: 'No, i want to manually select by profile(s)', value: 'selectProfiles' },
                    { title: 'No, i want to manually select user(s)', value: 'select' },
                ],
            });
            // Let users select profiles to reactivate users
            if (confirmSelect.value === 'selectProfiles') {
                const selectedProfileIds = await promptProfiles(flags['target-org'].getConnection(), {
                    multiselect: true,
                    returnField: 'Id',
                    message: 'Please select profiles that you want to reactivate users with .invalid emails',
                });
                usersToActivateFinal = usersToActivateFinal.filter((user) => selectedProfileIds.includes(user.ProfileId));
            }
            // Let users select users to reactivate
            else if (confirmSelect.value === 'select') {
                const usersSorted = sortArray(usersToActivate, {
                    by: ['Name', 'Email'],
                    order: ['asc'],
                });
                const selectUsers = await prompts({
                    type: 'multiselect',
                    name: 'value',
                    message: 'Please select users that you want to remove the .invalid from emails',
                    description: 'Choose specific users to reactivate by removing .invalid suffix from their email addresses',
                    choices: usersSorted.map((user) => {
                        return { title: `${user.Name} - ${user.Email}`, value: user };
                    }),
                });
                usersToActivateFinal = selectUsers.value;
            }
            else if (confirmSelect.value !== 'all') {
                const outputString = 'Script cancelled by user';
                uxLog("warning", this, c.yellow(outputString));
                return { outputString };
            }
        }
        // Process invalid users reactivation
        const userToActivateUpdated = usersToActivateFinal.map((user) => {
            const emailReplaced = user.Email.replace('.invalid', '');
            return { Id: user.Id, Email: emailReplaced };
        });
        const bulkUpdateRes = await bulkUpdate('User', 'update', userToActivateUpdated, conn);
        uxLog("action", this, c.cyan(`Results of the reactivation of ${userToActivateUpdated.length} users by removing the .invalid from their email`));
        uxLogTable(this, this.debugMode ? userToActivateUpdated : userToActivateUpdated.slice(0, this.maxUsersDisplay));
        if (!this.debugMode && userToActivateUpdated.length > this.maxUsersDisplay) {
            uxLog("warning", this, c.yellow(c.italic(`(list truncated to the first ${this.maxUsersDisplay} users)`)));
        }
        const activateSuccessNb = bulkUpdateRes.successfulResults.length;
        const activateErrorNb = bulkUpdateRes.failedResults.length;
        if (activateErrorNb > 0) {
            uxLog("warning", this, c.yellow(`Warning: ${c.red(c.bold(activateErrorNb))} users has not been reactivated (bulk API errors)`));
        }
        // Build results summary
        uxLog("success", this, c.green(`${c.bold(activateSuccessNb)} users has been be reactivated by removing the .invalid of their email`));
        // Return an object to be displayed with --json
        return {
            orgId: flags['target-org'].getOrgId(),
            activateSuccessNb: activateSuccessNb,
            activateErrorNb: activateErrorNb,
            outputString: `${activateSuccessNb} sandbox users has been be reactivated by removing the .invalid of their email`,
        };
    }
}
//# sourceMappingURL=activateinvalid.js.map