const { Controller } = require('libflitter')

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

    async get_banners(req, res, next) {
        const Message = this.models.get('Message')
        const messages = await Message.for_user(req.user)

        return res.api(messages.map(x => {
            return {
                message: x.message,
                expires: x.expires,
                dismissed: x.dismissed,
                type: x.display_type,
                id: x.id,
            }
        }))
    }

    async read_banner(req, res, next) {
        const banner_id = req.params.banner_id
        if ( !banner_id )
            return res.status(400)
                .message(`${req.T('api.missing_field')} banner_id`)
                .api()

        const Message = this.models.get('Message')
        const message = await Message.findById(banner_id)
        if ( !message )
            return res.status(404)
                .message(req.T('api.banner_not_found'))
                .api()

        if ( message.user_id !== req.user.id )
            return res.status(401).api()

        await message.dismiss()
        return res.api()
    }

    async create_banner(req, res, next) {
        // expires, display_type = info, message, user_id?
        const expires = req.body.expires
        const display_type = req.body.display_type || 'info'
        const message = req.body.message
        const user_ids = req.body.user_ids

        if ( !expires )
            return res.status(400)
                .message(`${req.T('api.missing_field')} expires`)
                .api()

        if ( !message )
            return res.status(400)
                .message(`${req.T('api.missing_field')} message`)
                .api()


    }
}

module.exports = exports = MessageController
