const { Unit } = require('libflitter')

class SettingsUnit extends Unit {
    static get name() {
        return 'settings'
    }

    static get services() {
        return [...super.services, 'configs', 'models', 'output']
    }

    async go(app) {
        Error.stackTraceLimit = 50
        app.express.set('trust proxy', true)

        const User = this.models.get('auth:User')
        const user = await User.findOne({is_default_user_for_coreid: true})
        if ( !user ) {
            const user = new User({
                uid: '__coreid_default_user__',
                provider: 'flitter',
                block_login: true,
                first_name: 'Default_User',
                last_name: 'Default_User',
                ldap_visible: false,
                is_default_user_for_coreid: true,
            })

            await user.save()
        }

        const Setting = this.models.get('Setting')
        const default_settings = this.configs.get('setting.settings')
        for ( const key in default_settings ) {
            if ( !default_settings.hasOwnProperty(key) ) continue
            const default_value = default_settings[key]
            this.output.debug(`Guarantee setting key "${key}" with default value "${default_value}".`)
            await Setting.guarantee(key, default_value)
        }

        const Permission = this.models.get('iam:Permission')
        const default_permissions = this.configs.get('auth.iam.default_permissions')
        for ( const perm of default_permissions ) {
            const existing = await Permission.findOne(perm)
            if ( !existing ) {
                await (new Permission(perm)).save()
            }
        }
    }
}

module.exports = exports = SettingsUnit
