import { z } from 'zod';
import auth from '../../../Auth.js';
import commands from '../commands.js';
import Command, { CommandError, globalOptionsZod } from '../../../Command.js';
import { formatting } from '../../../utils/formatting.js';
import { cli } from '../../../cli/cli.js';
export const options = z.strictObject({
    ...globalOptionsZod.shape,
    name: z.string().optional().alias('n')
});
class ConnectionUseCommand extends Command {
    get name() {
        return commands.USE;
    }
    get description() {
        return 'Activates the specified Microsoft 365 tenant connection';
    }
    get schema() {
        return options;
    }
    async commandAction(logger, args) {
        let connection;
        if (args.options.name) {
            connection = await auth.getConnection(args.options.name);
        }
        else {
            const connections = await auth.getAllConnections();
            connections.sort((a, b) => a.name.localeCompare(b.name));
            const keyValuePair = formatting.convertArrayToHashTable('name', connections);
            connection = await cli.handleMultipleResultsFound('Please select the connection you want to activate.', keyValuePair);
        }
        if (this.verbose) {
            await logger.logToStderr(`Switching to connection '${connection.identityName}', appId: ${connection.appId}, tenantId: ${connection.identityTenantId}...`);
        }
        await auth.switchToConnection(connection);
        const details = auth.getConnectionDetails(auth.connection);
        if (this.debug) {
            details.accessTokens = JSON.stringify(auth.connection.accessTokens, null, 2);
        }
        await logger.log(details);
    }
    async action(logger, args) {
        try {
            await auth.restoreAuth();
        }
        catch (error) {
            throw new CommandError(error);
        }
        await this.initAction(args, logger);
        await this.commandAction(logger, args);
    }
}
export default new ConnectionUseCommand();
//# sourceMappingURL=connection-use.js.map