import { z } from 'zod';
import { globalOptionsZod } from '../../../../Command.js';
import GraphCommand from '../../../base/GraphCommand.js';
import commands from '../../commands.js';
import { validation } from '../../../../utils/validation.js';
import { entraUser } from '../../../../utils/entraUser.js';
import { entraGroup } from '../../../../utils/entraGroup.js';
import { odata } from '../../../../utils/odata.js';
export const options = z.strictObject({
    ...globalOptionsZod.shape,
    userId: z.uuid().optional(),
    userName: z.string().refine(upn => validation.isValidUserPrincipalName(upn), {
        error: e => `'${e.input}' is not a valid user principal name for option 'userName'.`
    }).optional(),
    groupId: z.uuid().optional(),
    groupName: z.string().optional(),
    withPrincipalDetails: z.boolean().default(false)
});
class EntraPimRoleAssignmentEligibilityListCommand extends GraphCommand {
    get name() {
        return commands.PIM_ROLE_ASSIGNMENT_ELIGIBILITY_LIST;
    }
    get description() {
        return 'Retrieves a list of eligible roles a user or group can be assigned to';
    }
    get schema() {
        return options;
    }
    getRefinedSchema(schema) {
        return schema
            .refine(options => {
            const specified = [options.userId, options.userName, options.groupId, options.groupName].filter(o => o !== undefined).length;
            return specified <= 1;
        }, {
            message: 'Specify only one of the following options: userId, userName, groupId, groupName',
            params: {
                customCode: 'optionSet',
                options: ['userId', 'userName', 'groupId', 'groupName']
            }
        });
    }
    defaultProperties() {
        return ['roleDefinitionId', 'roleDefinitionName', 'principalId'];
    }
    async commandAction(logger, args) {
        if (this.verbose) {
            await logger.logToStderr(`Retrieving list of eligible roles for ${args.options.userId || args.options.userName || args.options.groupId || args.options.groupName || 'all users'}...`);
        }
        const queryParameters = [];
        const expands = [];
        try {
            const principalId = await this.getPrincipalId(logger, args.options);
            if (principalId) {
                queryParameters.push(`$filter=principalId eq '${principalId}'`);
            }
            expands.push('roleDefinition($select=displayName)');
            if (args.options.withPrincipalDetails) {
                expands.push('principal');
            }
            queryParameters.push(`$expand=${expands.join(',')}`);
            const url = `${this.resource}/v1.0/roleManagement/directory/roleEligibilityScheduleInstances?${queryParameters.join('&')}`;
            const results = await odata.getAllItems(url);
            results.forEach(c => {
                const roleDefinition = c['roleDefinition'];
                if (roleDefinition) {
                    c.roleDefinitionName = roleDefinition.displayName;
                }
                delete c['roleDefinition'];
            });
            await logger.log(results);
        }
        catch (err) {
            this.handleRejectedODataJsonPromise(err);
        }
    }
    async getPrincipalId(logger, options) {
        let principalId = options.userId;
        if (options.userName) {
            if (this.verbose) {
                await logger.logToStderr(`Retrieving user by its name '${options.userName}'`);
            }
            principalId = await entraUser.getUserIdByUpn(options.userName);
        }
        else if (options.groupId) {
            principalId = options.groupId;
        }
        else if (options.groupName) {
            if (this.verbose) {
                await logger.logToStderr(`Retrieving group by its name '${options.groupName}'`);
            }
            principalId = await entraGroup.getGroupIdByDisplayName(options.groupName);
        }
        return principalId;
    }
}
export default new EntraPimRoleAssignmentEligibilityListCommand();
//# sourceMappingURL=pim-role-assignment-eligibility-list.js.map