import { z } from 'zod';
import { globalOptionsZod } from '../../../../Command.js';
import request from '../../../../request.js';
import { formatting } from '../../../../utils/formatting.js';
import { odata } from '../../../../utils/odata.js';
import { validation } from '../../../../utils/validation.js';
import PowerAutomateCommand from '../../../base/PowerAutomateCommand.js';
import commands from '../../commands.js';
export const options = z.strictObject({
    ...globalOptionsZod.shape,
    flowName: z.uuid(),
    environmentName: z.string().alias('e'),
    status: z.enum(['Succeeded', 'Running', 'Failed', 'Cancelled']).optional(),
    triggerStartTime: z.string().refine(date => validation.isValidISODateTime(date), {
        error: e => `'${e.input}' is not a valid datetime.`
    }).optional(),
    triggerEndTime: z.string().refine(date => validation.isValidISODateTime(date), {
        error: e => `'${e.input}' is not a valid datetime.`
    }).optional(),
    withTrigger: z.boolean().optional(),
    asAdmin: z.boolean().optional()
});
class FlowRunListCommand extends PowerAutomateCommand {
    get name() {
        return commands.RUN_LIST;
    }
    get description() {
        return 'Lists runs of the specified Microsoft Flow';
    }
    get schema() {
        return options;
    }
    getRefinedSchema(schema) {
        return schema.refine(options => {
            if (options.output !== 'json' && options.withTrigger) {
                return false;
            }
            return true;
        }, {
            error: 'The --withTrigger option is only available when output is set to json'
        });
    }
    defaultProperties() {
        return ['name', 'startTime', 'status'];
    }
    async commandAction(logger, args) {
        if (this.verbose) {
            await logger.logToStderr(`Retrieving list of runs for Microsoft Flow ${args.options.flowName}...`);
        }
        let url = `${PowerAutomateCommand.resource}/providers/Microsoft.ProcessSimple/${args.options.asAdmin ? 'scopes/admin/' : ''}environments/${formatting.encodeQueryParameter(args.options.environmentName)}/flows/${formatting.encodeQueryParameter(args.options.flowName)}/runs?api-version=2016-11-01`;
        const filters = this.getFilters(args.options);
        if (filters.length > 0) {
            url += `&$filter=${filters.join(' and ')}`;
        }
        try {
            const items = await odata.getAllItems(url);
            if (args.options.withTrigger) {
                await this.retrieveTriggerInformation(items);
            }
            if (args.options.output !== 'json' && items.length > 0) {
                items.forEach(i => {
                    i.startTime = i.properties.startTime;
                    i.status = i.properties.status;
                });
            }
            await logger.log(items);
        }
        catch (err) {
            this.handleRejectedODataJsonPromise(err);
        }
    }
    getFilters(options) {
        const filters = [];
        if (options.status) {
            filters.push(`status eq '${options.status}'`);
        }
        if (options.triggerStartTime) {
            filters.push(`startTime ge ${options.triggerStartTime}`);
        }
        if (options.triggerEndTime) {
            filters.push(`startTime lt ${options.triggerEndTime}`);
        }
        return filters;
    }
    async retrieveTriggerInformation(items) {
        const tasks = items.map(async (item) => {
            const requestOptions = {
                url: item.properties.trigger.outputsLink.uri,
                headers: {
                    accept: 'application/json',
                    'x-anonymous': true
                },
                responseType: 'json'
            };
            const response = await request.get(requestOptions);
            item.triggerInformation = response.body;
        });
        await Promise.all(tasks);
    }
}
export default new FlowRunListCommand();
//# sourceMappingURL=run-list.js.map