"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const commandTypes_1 = require("@mablhq-internal/runtime/core/commandTypes");
const constants_1 = require("../../../constants");
const constants_2 = require("@mablhq-internal/runtime/core/constants");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const describe_1 = require("../../../commandUtil/describe");
exports.command = `list <${constants_2.CommandArgId}>`;
exports.describe = 'Show build files associated with an environment';
exports.builder = (yargs) => {
    yargs
        .positional(constants_2.CommandArgId, {
        describe: 'Environment ID to list build file associations for',
        type: 'string',
    })
        .option(constants_2.CommandArgApplicationId, {
        describe: 'Application ID to filter build files by',
        alias: constants_1.CommandArgAliases.ApplicationId,
        nargs: 1,
        type: 'string',
    })
        .option(constants_1.CommandArgLimitOutput, {
        alias: constants_1.CommandArgAliases.LimitOutput,
        describe: `The number of build files to return'`,
        default: commandTypes_1.DEFAULT_LISTING_RESULT_LIMIT,
        nargs: 1,
        type: 'string',
    })
        .option(constants_1.CommandArgOutput, {
        alias: constants_1.CommandArgAliases.OutputType,
        choices: constants_1.DefaultOutputFormatChoices,
        describe: 'Specify result output format',
        nargs: 1,
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(queryDeployments);
async function queryDeployments(parsed) {
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    try {
        const environment = await apiClient.getEnvironment(parsed.id);
        const deploymentEntities = await apiClient.queryDeploymentEntities(environment.organization_id ?? '', environment.id, parsed[constants_2.CommandArgApplicationId], parsed.limit);
        const mobileDeployments = deploymentEntities.deployments?.filter((deployment) => !!deployment.mobile_app_file_id) ?? [];
        const mobileBuildFiles = await Promise.all(mobileDeployments.map((deployment) => apiClient.getMobileAppFile(deployment.mobile_app_file_id)));
        (0, describe_1.outputEntity)(mobileDeployments.map((deployment, index) => ({
            ...deployment,
            mobile_app_file: mobileBuildFiles[index],
        })), parsed.output);
    }
    catch (error) {
        throw new Error(`Error listing build files for environment ${parsed.id}: ${error}`);
    }
    return 'done';
}
