import { z } from 'zod';
import { globalOptionsZod } from '../../../../Command.js';
import { cli } from '../../../../cli/cli.js';
import request from '../../../../request.js';
import { formatting } from '../../../../utils/formatting.js';
import { validation } from '../../../../utils/validation.js';
import PowerAppsCommand from '../../../base/PowerAppsCommand.js';
import commands from '../../commands.js';
import paAppListCommand from '../app/app-list.js';
export const options = z.strictObject({
    ...globalOptionsZod.shape,
    name: z.string()
        .refine(val => validation.isValidGuid(val), {
        message: 'The value is not a valid GUID.'
    })
        .optional()
        .alias('n'),
    displayName: z.string().optional().alias('d'),
    environmentName: z.string().optional().alias('e'),
    asAdmin: z.boolean().optional()
});
class PaAppGetCommand extends PowerAppsCommand {
    get name() {
        return commands.APP_GET;
    }
    get description() {
        return 'Gets information about the specified Microsoft Power App';
    }
    get schema() {
        return options;
    }
    getRefinedSchema(schema) {
        return schema
            .refine(opts => [opts.name, opts.displayName].filter(x => x !== undefined).length === 1, {
            error: `Specify either 'name' or 'displayName', but not both.`,
            params: {
                customCode: 'optionSet',
                options: ['name', 'displayName']
            }
        })
            .refine(opts => !opts.asAdmin || opts.environmentName, {
            message: 'When specifying the asAdmin option, the environment option is required as well.'
        })
            .refine(opts => !opts.environmentName || opts.asAdmin, {
            message: 'When specifying the environment option, the asAdmin option is required as well.'
        });
    }
    async commandAction(logger, args) {
        try {
            if (args.options.name) {
                let endpoint = `${this.resource}/providers/Microsoft.PowerApps`;
                if (args.options.asAdmin) {
                    endpoint += `/scopes/admin/environments/${formatting.encodeQueryParameter(args.options.environmentName)}`;
                }
                endpoint += `/apps/${formatting.encodeQueryParameter(args.options.name)}?api-version=2016-11-01`;
                const requestOptions = {
                    url: endpoint,
                    headers: {
                        accept: 'application/json'
                    },
                    responseType: 'json'
                };
                if (this.verbose) {
                    await logger.logToStderr(`Retrieving information about Microsoft Power App with name '${args.options.name}'...`);
                }
                const res = await request.get(requestOptions);
                await logger.log(this.setProperties(res));
            }
            else {
                if (this.verbose) {
                    await logger.logToStderr(`Retrieving information about Microsoft Power App with displayName '${args.options.displayName}'...`);
                }
                const getAppsOutput = await this.getApps(args, logger);
                if (getAppsOutput.stdout && JSON.parse(getAppsOutput.stdout).length > 0) {
                    const allApps = JSON.parse(getAppsOutput.stdout);
                    const app = allApps.find((a) => {
                        return a.properties.displayName.toLowerCase() === `${args.options.displayName}`.toLowerCase();
                    });
                    if (app) {
                        await logger.log(this.setProperties(app));
                    }
                    else {
                        throw `No app found with displayName '${args.options.displayName}'.`;
                    }
                }
                else {
                    throw 'No apps found.';
                }
            }
        }
        catch (err) {
            this.handleRejectedODataJsonPromise(err);
        }
    }
    async getApps(args, logger) {
        if (this.verbose) {
            await logger.logToStderr(`Retrieving all apps...`);
        }
        const options = {
            output: 'json',
            debug: this.debug,
            verbose: this.verbose,
            environmentName: args.options.environmentName,
            asAdmin: args.options.asAdmin
        };
        return await cli.executeCommandWithOutput(paAppListCommand, { options: { ...options, _: [] } });
    }
    setProperties(app) {
        app.displayName = app.properties.displayName;
        app.description = app.properties.description || '';
        app.appVersion = app.properties.appVersion;
        app.owner = app.properties.owner.email || '';
        return app;
    }
}
export default new PaAppGetCommand();
//# sourceMappingURL=app-get.js.map