"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "FirstTimeSetupController", {
    enumerable: true,
    get: function() {
        return FirstTimeSetupController;
    }
});
const _awilixexpress = require("awilix-express");
const _serverconstants = require("../server.constants");
const _validators = require("../handlers/validators");
const _settingvalidation = require("./validation/setting.validation");
const _runtimeexceptions = require("../exceptions/runtime.exceptions");
const _authorizationconstants = require("../constants/authorization.constants");
const _settingsstore = require("../state/settings.store");
const _express = require("express");
const _userserviceinterface = require("../services/interfaces/user-service.interface");
const _roleserviceinterface = require("../services/interfaces/role-service.interface");
const _yamlservice = require("../services/core/yaml.service");
const _multerservice = require("../services/core/multer.service");
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
}
class FirstTimeSetupController {
    settingsStore;
    roleService;
    userService;
    yamlService;
    multerService;
    constructor(settingsStore, roleService, userService, yamlService, multerService){
        this.settingsStore = settingsStore;
        this.roleService = roleService;
        this.userService = userService;
        this.yamlService = yamlService;
        this.multerService = multerService;
    }
    async validateWizard(req, res) {
        const { rootUsername } = await (0, _validators.validateMiddleware)(req, _settingvalidation.wizardSettingsSchema);
        await this.roleService.getSynchronizedRoleByName(_authorizationconstants.ROLES.ADMIN);
        if (this.settingsStore.isWizardCompleted()) {
            throw new _runtimeexceptions.ForbiddenError("Wizard already completed");
        }
        const user = await this.userService.findRawByUsername(rootUsername?.toLowerCase());
        if (user) {
            throw new _runtimeexceptions.BadRequestException("This user already exists");
        }
        return res.send();
    }
    async completeWizard(req, res) {
        const { loginRequired, registration, rootUsername, rootPassword } = await (0, _validators.validateMiddleware)(req, _settingvalidation.wizardSettingsSchema);
        if (this.settingsStore.isWizardCompleted()) {
            throw new _runtimeexceptions.ForbiddenError("Wizard already completed");
        }
        await this.roleService.getSynchronizedRoleByName(_authorizationconstants.ROLES.ADMIN);
        const user = await this.userService.findRawByUsername(rootUsername?.toLowerCase());
        if (user) {
            throw new _runtimeexceptions.BadRequestException("This user already exists");
        }
        await this.userService.register({
            username: rootUsername,
            password: rootPassword,
            roles: [
                _authorizationconstants.ROLES.ADMIN
            ],
            isRootUser: true,
            isVerified: true,
            isDemoUser: false,
            needsPasswordChange: false
        });
        await this.settingsStore.setLoginRequired(loginRequired);
        await this.settingsStore.setRegistrationEnabled(registration);
        await this.settingsStore.setWizardCompleted(_serverconstants.AppConstants.currentWizardVersion);
        return res.send();
    }
    async importYamlFile(req, res) {
        if (this.settingsStore.isWizardCompleted()) {
            throw new _runtimeexceptions.ForbiddenError("Wizard already completed. Cannot import during first-time setup once wizard is complete.");
        }
        const files = await this.multerService.multerLoadFileAsync(req, res, [
            ".yaml",
            ".yml"
        ], false);
        const firstFile = files[0];
        await this.yamlService.importYaml(firstFile.buffer.toString());
        return res.send({
            success: true
        });
    }
}
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/validate"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], FirstTimeSetupController.prototype, "validateWizard", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/complete"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], FirstTimeSetupController.prototype, "completeWizard", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/yaml-import"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], FirstTimeSetupController.prototype, "importYamlFile", null);
FirstTimeSetupController = _ts_decorate([
    (0, _awilixexpress.route)(_serverconstants.AppConstants.apiRoute + "/first-time-setup"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _settingsstore.SettingsStore === "undefined" ? Object : _settingsstore.SettingsStore,
        typeof _roleserviceinterface.IRoleService === "undefined" ? Object : _roleserviceinterface.IRoleService,
        typeof _userserviceinterface.IUserService === "undefined" ? Object : _userserviceinterface.IUserService,
        typeof _yamlservice.YamlService === "undefined" ? Object : _yamlservice.YamlService,
        typeof _multerservice.MulterService === "undefined" ? Object : _multerservice.MulterService
    ])
], FirstTimeSetupController);

//# sourceMappingURL=first-time-setup.controller.js.map