"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RegisterAppCommand = void 0;
const config_1 = require("../config");
const file_system_1 = require("../file-system");
const ui_1 = require("../ui");
class RegisterAppCommand {
    appClient;
    appConfigReader;
    appConfigWriter;
    logger;
    configFile;
    constructor(appClient, appConfigReader, appConfigWriter, logger, configFile) {
        this.appClient = appClient;
        this.appConfigReader = appConfigReader;
        this.appConfigWriter = appConfigWriter;
        this.logger = logger;
        this.configFile = configFile;
    }
    async execute(input, { shouldPrependAppName = false } = {}) {
        const result = await this.registerApp(input, '.', { shouldPrependAppName });
        return {
            analytics: { appId: result.id, appName: input.name },
            environments: result.environments.map((env) => env.key)
        };
    }
    async registerApp(input, directory, { shouldPrependAppName, requiredProduct }) {
        this.logger.info(ui_1.Text.create.taskRegister);
        const result = await this.appClient.createApp(input);
        await (0, file_system_1.inDirectory)(directory, async () => {
            const { modules } = await this.configFile.readConfig();
            if (modules) {
                const uiKit1Modules = (0, config_1.findUIKit1Modules)(modules);
                if (uiKit1Modules.length > 0) {
                    this.logger.warn(ui_1.Text.warning.deprecation.uikit(uiKit1Modules));
                }
            }
            const section = await this.appConfigReader.readConfigSection();
            let newAppDetails = {
                id: result.id,
                ...(requiredProduct && {
                    compatibility: {
                        [requiredProduct]: {
                            required: true
                        }
                    }
                })
            };
            if (section !== 'invalid' && section !== 'missing') {
                newAppDetails = {
                    ...section,
                    ...newAppDetails
                };
            }
            await this.appConfigWriter.writeConfigSection(newAppDetails);
            if (shouldPrependAppName) {
                await this.appConfigWriter.prependAppNameToModules(input.name);
            }
        });
        this.logger.info(ui_1.Text.create.taskCreateEnvironments);
        return result;
    }
}
exports.RegisterAppCommand = RegisterAppCommand;
