const { Controller } = require('libflitter')

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

    async get_session(req, res, next) {
        return res.api(await this.session_data(req.user))
    }

    async save_session(req, res, next) {
        if ( req?.body?.user?.preferences ) {
            const save_prefs = req.body.user.preferences;
            req.user.preferences.dark_mode = !!save_prefs.dark_mode;

            if ( save_prefs.default_page ) {
                req.user.preferences.default_page = save_prefs.default_page;
            } else {
                req.user.preferences.default_page = '';
            }

            req.user.preferences.auto_prefetch = !!save_prefs.auto_prefetch
        }

        await req.user.save()
        return res.api()
    }

    async session_data(user) {
        return {
            user: {
                id: user.id,
                username: user.uid,
                preferences: user.preferences || {},
            },
            app: {
                name: this.configs.get('app.name'),
                url: this.configs.get('app.url'),
            },
        }
    }

    async get_device_token(req, res, next) {
        const DeviceToken = this.models.get('api:DeviceToken')
        const token = await DeviceToken.grant_user(req.user)

        return res.api({
            token: token.token,
            expiration_date: token.expiration_date,
        })
    }

    async resume(req, res, next) {
        const DeviceToken = this.models.get('api:DeviceToken')
        const User = this.models.get('auth:User')
        const token = await DeviceToken.findOne({
            token: req.params.token,
            expiration_date: { $gt: new Date },
        });

        if ( !token ) {
            return res.status(404)
                .message('Device token expired or invalid.')
                .api()
        }

        const user = await User.findById(token.user_id);
        if ( !user ) {
            return res.status(404)
                .message('Device token expired or invalid.')
                .api()
        }

        await this.auth.get_provider().session(req, user)
        return res.api()
    }
}

module.exports = exports = SessionController
