import { z } from 'zod';
import { globalOptionsZod } from '../../../Command.js';
import { formatting } from '../../../utils/formatting.js';
import { odata } from '../../../utils/odata.js';
import PowerAutomateCommand from '../../base/PowerAutomateCommand.js';
import commands from '../commands.js';
export const options = z.strictObject({
    ...globalOptionsZod.shape,
    environmentName: z.string().alias('e'),
    sharingStatus: z.enum(['all', 'personal', 'ownedByMe', 'sharedWithMe']).optional(),
    withSolutions: z.boolean().optional(),
    asAdmin: z.boolean().optional()
});
class FlowListCommand extends PowerAutomateCommand {
    get name() {
        return commands.LIST;
    }
    get description() {
        return 'Lists Power Automate flows in the given environment';
    }
    get schema() {
        return options;
    }
    getRefinedSchema(schema) {
        return schema.refine(options => !(options.asAdmin && options.sharingStatus), {
            error: 'The options asAdmin and sharingStatus cannot be specified together.'
        });
    }
    defaultProperties() {
        return ['name', 'displayName'];
    }
    async commandAction(logger, args) {
        if (this.verbose) {
            await logger.logToStderr(`Getting Power Automate flows${args.options.asAdmin ? ' as admin' : ''} in environment '${args.options.environmentName}'...`);
        }
        try {
            const { environmentName, asAdmin, sharingStatus, withSolutions } = args.options;
            let items = [];
            if (sharingStatus === 'personal') {
                const url = this.getApiUrl(environmentName, asAdmin, withSolutions, 'personal');
                items = await odata.getAllItems(url);
            }
            else if (sharingStatus === 'sharedWithMe') {
                const url = this.getApiUrl(environmentName, asAdmin, withSolutions, 'team');
                items = await odata.getAllItems(url);
            }
            else if (sharingStatus === 'all') {
                let url = this.getApiUrl(environmentName, asAdmin, withSolutions, 'personal');
                items = await odata.getAllItems(url);
                url = this.getApiUrl(environmentName, asAdmin, withSolutions, 'team');
                const teamFlows = await odata.getAllItems(url);
                items = items.concat(teamFlows);
            }
            else {
                const url = this.getApiUrl(environmentName, asAdmin, withSolutions);
                items = await odata.getAllItems(url);
            }
            // Remove duplicates
            items = items.filter((flow, index, self) => index === self.findIndex(f => f.id === flow.id));
            if (args.options.output && args.options.output !== 'json') {
                items.forEach(flow => {
                    flow.displayName = flow.properties.displayName;
                });
            }
            await logger.log(items);
        }
        catch (err) {
            this.handleRejectedODataJsonPromise(err);
        }
    }
    getApiUrl(environmentName, asAdmin, includeSolutionFlows, filter) {
        const baseEndpoint = `${PowerAutomateCommand.resource}/providers/Microsoft.ProcessSimple`;
        const environmentSegment = `/environments/${formatting.encodeQueryParameter(environmentName)}`;
        const adminSegment = `/scopes/admin${environmentSegment}/v2`;
        const flowsEndpoint = '/flows?api-version=2016-11-01';
        const filterQuery = filter === 'personal' || filter === 'team' ? `&$filter=search('${filter}')` : '';
        const includeQuery = includeSolutionFlows ? '&include=includeSolutionCloudFlows' : '';
        return `${baseEndpoint}${asAdmin ? adminSegment : environmentSegment}${flowsEndpoint}${filterQuery}${includeQuery}`;
    }
}
export default new FlowListCommand();
//# sourceMappingURL=flow-list.js.map