import {
    generateOTPQRCode,
    generateOTPSecret,
    validateOTPCode,
    saveOTPSecret
} from "../../../lib/otp.mjs";

import {
    getUser,
    getUserMFA
} from "../../../lib/mysql.mjs";

export const get = async function (request, response) {
    if (request.getAuthState() != 'authenticated') {
        response.redirect('/login');
        return;
    }

    if (typeof request.session.otpConfig != 'object') {
        request.session.otpConfig = {
            completed: false,
            otpSecret: await generateOTPSecret()
        }
    }

    let userData = await getUser(request.session.userid);
    let otpsecret = request.session.otpConfig.otpSecret;

    response.render(`ui/profile.njk`, {
        page: 'otp/create',
        otp: {
            active: request.session.otpConfig.completed != '' ? true : false,
            qrcode: await generateOTPQRCode(userData.name, otpsecret),
            otpsecret: request.session.otpConfig.otpSecret
        }
    });
}


export const post = async function (request, response) {
    if (request.getAuthState() != 'authenticated') {
        response.redirect('/login');
        return;
    }

    let userData = await getUser(request.session.userid);

    if (validateOTPCode(userData.name, request.body.otpsecret, request.body.otpcode)) {
        saveOTPSecret(request.session.userid, request.body.otpsecret)

        response.render(`ui/messages/success.njk`, {
            message: {
                title: 'OTP Secret created!',
                text: 'Your new OTP-Secret was successfull generated',
                link: '/profile/security'
            }
        });
    } else {
        response.redirect('/profile/otp/create')
    }

}