import { z } from 'zod';
import { globalOptionsZod } from '../../../../Command.js';
import request from '../../../../request.js';
import { validation } from '../../../../utils/validation.js';
import GraphCommand from '../../../base/GraphCommand.js';
import commands from '../../commands.js';
import { entraUser } from '../../../../utils/entraUser.js';
import { formatting } from '../../../../utils/formatting.js';
export const options = z.strictObject({
    ...globalOptionsZod.shape,
    id: z.uuid().optional().alias('i'),
    userName: z.string().refine(name => validation.isValidUserPrincipalName(name), {
        error: e => `'${e.input}' is not a valid userName.`
    }).optional().alias('n'),
    email: z.string().optional(),
    properties: z.string().optional().alias('p'),
    withManager: z.boolean().optional()
});
class EntraUserGetCommand extends GraphCommand {
    get name() {
        return commands.USER_GET;
    }
    get description() {
        return 'Gets information about the specified user';
    }
    get schema() {
        return options;
    }
    getRefinedSchema(schema) {
        return schema
            .refine(options => [options.id, options.userName, options.email].filter(o => o !== undefined).length === 1, {
            error: `Specify either 'id', 'userName', or 'email'.`,
            params: {
                customCode: 'optionSet',
                options: ['id', 'userName', 'email']
            }
        });
    }
    async commandAction(logger, args) {
        try {
            let userIdOrPrincipalName = args.options.id;
            if (args.options.userName) {
                // single user can be retrieved also by user principal name
                userIdOrPrincipalName = formatting.encodeQueryParameter(args.options.userName);
            }
            else if (args.options.email) {
                userIdOrPrincipalName = await entraUser.getUserIdByEmail(args.options.email);
            }
            const requestUrl = this.getRequestUrl(userIdOrPrincipalName, args.options);
            const requestOptions = {
                url: requestUrl,
                headers: {
                    accept: 'application/json;odata.metadata=none'
                },
                responseType: 'json'
            };
            const user = await request.get(requestOptions);
            await logger.log(user);
        }
        catch (err) {
            this.handleRejectedODataJsonPromise(err);
        }
    }
    getRequestUrl(userIdOrPrincipalName, options) {
        const queryParameters = [];
        if (options.properties) {
            const allProperties = options.properties.split(',');
            const selectProperties = allProperties.filter(prop => !prop.includes('/'));
            if (selectProperties.length > 0) {
                queryParameters.push(`$select=${selectProperties}`);
            }
        }
        if (options.withManager) {
            queryParameters.push('$expand=manager($select=displayName,userPrincipalName,id,mail)');
        }
        const queryString = queryParameters.length > 0
            ? `?${queryParameters.join('&')}`
            : '';
        // user principal name can start with $ but it violates the OData URL convention, so it must be enclosed in parenthesis and single quotes
        return userIdOrPrincipalName.startsWith('%24')
            ? `${this.resource}/v1.0/users('${userIdOrPrincipalName}')${queryString}`
            : `${this.resource}/v1.0/users/${userIdOrPrincipalName}${queryString}`;
    }
}
export default new EntraUserGetCommand();
//# sourceMappingURL=user-get.js.map