const { Controller } = require('libflitter')

class SettingsController extends Controller {
    static get services() {
        return [...super.services, 'models']
    }

    async get_settings(req, res, next) {
        const Setting = this.models.get('Setting')
        const settings = await Setting.find()
        const data = []

        for ( const setting of settings ) {
            data.push(await setting.to_api())
        }

        return res.api(data)
    }

    async get_setting(req, res, next) {
        const Setting = this.models.get('Setting')
        const setting = await Setting.findOne({ key: req.params.key })

        if ( !setting )
            return res.status(404)
                .message(req.T('api.setting_not_found'))
                .api()

        return res.api(await setting.to_api())
    }

    async update_setting(req, res, next) {
        const Setting = this.models.get('Setting')
        const setting = await Setting.findOne({ key: req.params.key })

        if ( !setting )
            return res.status(404)
                .message(req.T('api.setting_not_found'))
                .api()

        setting.set(req.body.value)
        await setting.save()
        return res.api()
    }
}

module.exports = exports = SettingsController
