import { z } from 'zod';
import { globalOptionsZod } from '../../../../Command.js';
import request from '../../../../request.js';
import { formatting } from '../../../../utils/formatting.js';
import GraphCommand from '../../../base/GraphCommand.js';
import commands from '../../commands.js';
import { cli } from '../../../../cli/cli.js';
export const options = z.strictObject({
    ...globalOptionsZod.shape,
    id: z.uuid().optional().alias('i'),
    displayName: z.string().optional().alias('n'),
    objectId: z.uuid().optional()
});
class EntraEnterpriseAppAddCommand extends GraphCommand {
    get name() {
        return commands.ENTERPRISEAPP_ADD;
    }
    get description() {
        return 'Creates an enterprise application (or service principal) for a registered Entra app';
    }
    alias() {
        return [commands.SP_ADD];
    }
    get schema() {
        return options;
    }
    getRefinedSchema(schema) {
        return schema
            .refine(options => [options.id, options.displayName, options.objectId].filter(o => o !== undefined).length === 1, {
            error: 'Specify either id, displayName, or objectId',
            params: {
                customCode: 'optionSet',
                options: ['id', 'displayName', 'objectId']
            }
        });
    }
    async getAppId(args) {
        if (args.options.id) {
            return args.options.id;
        }
        let spMatchQuery = '';
        if (args.options.displayName) {
            spMatchQuery = `displayName eq '${formatting.encodeQueryParameter(args.options.displayName)}'`;
        }
        else if (args.options.objectId) {
            spMatchQuery = `id eq '${formatting.encodeQueryParameter(args.options.objectId)}'`;
        }
        const appIdRequestOptions = {
            url: `${this.resource}/v1.0/applications?$filter=${spMatchQuery}`,
            headers: {
                accept: 'application/json;odata.metadata=none'
            },
            responseType: 'json'
        };
        const response = await request.get(appIdRequestOptions);
        const spItem = response.value[0];
        if (!spItem) {
            throw `The specified Entra app doesn't exist`;
        }
        if (response.value.length > 1) {
            const resultAsKeyValuePair = formatting.convertArrayToHashTable('appId', response.value);
            const result = await cli.handleMultipleResultsFound(`Multiple Entra apps with name '${args.options.displayName}' found.`, resultAsKeyValuePair);
            return result.appId;
        }
        return spItem.appId;
    }
    async commandAction(logger, args) {
        try {
            const appId = await this.getAppId(args);
            const requestOptions = {
                url: `${this.resource}/v1.0/servicePrincipals`,
                headers: {
                    accept: 'application/json;odata.metadata=none',
                    'content-type': 'application/json;odata=nometadata'
                },
                data: {
                    appId: appId
                },
                responseType: 'json'
            };
            const res = await request.post(requestOptions);
            await logger.log(res);
        }
        catch (err) {
            this.handleRejectedODataJsonPromise(err);
        }
    }
}
export default new EntraEnterpriseAppAddCommand();
//# sourceMappingURL=enterpriseapp-add.js.map