const { Controller } = require('libflitter')

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

    async setup(req, res, next) {
        if ( req.user.mfa_enabled ) {
            // Already set up!
            return this.Vue.auth_message(res, {
                message: req.T('auth.already_mfa'),
                next_destination: '/dash/profile',
                button_text: 'Okay',
            })
        }

        // Display the token setup page
        return res.page('auth:mfa:setup', {
            ...this.Vue.data()
        })
    }

    async challenge(req, res, next) {
        if ( !req.user.mfa_enabled ) {
            return this.Vue.auth_message(res, {
                message: req.T('auth.mfa_prompt'),
                next_destination: '/auth/mfa/setup',
                button_text: 'Setup MFA',
            })
        }

        if ( !req.trap.has_trap('mfa_challenge') ) {
            return res.redirect(req.session.auth.flow)
        }

        // Display the MFA challenge page
        return res.page('auth:mfa:challenge', {
            ...this.Vue.data()
        })
    }

    async get_disable(req, res, next) {
        return this.Vue.confirm(res, {
            message: req.T('auth.mfa_disable_prompt'),
            yes: '/auth/mfa/disable/process',
            no: '/dash/profile',
        })
    }

    async do_disable(req, res, next) {
        return res.page('auth:mfa:disable', {
            ...this.Vue.data(),
            ...this.Vue.session(req),
        })
    }

    async get_recovery(req, res, next) {
        if (
            !req.user.mfa_enabled
            || !Array.isArray(req.user.mfa_token.recovery_codes)
            || req.user.mfa_token.recovery_codes.length < 1
        ) return this.Vue.auth_message(res, {
            message: req.T('auth.mfa_no_recovery'),
            next_destination: '/auth/mfa/challenge',
            button_text: 'Go Back',
        })

        return res.page('auth:mfa:recovery', {
            ...this.Vue.data(),
            ...this.Vue.session(req),
        })
    }
}

module.exports = exports = MFAController
