import qrcode from "qrcode";

import {
    Secret,
    TOTP
} from "otpauth";

import {
    getConfig
} from "./config.mjs";

import {
    setOTPSecret
} from "./mysql.mjs";

let appConfig = await getConfig();

export function generateOTPSecret() {
    return new Promise((resolve, reject) => {
        let otpSecret = new Secret({ length: 20 });
        resolve(otpSecret.base32);
    })
}

export function generateOTPQRCode(account, otpsecret) {
    return new Promise(async (resolve, reject) => {
        let totp = new TOTP({
            issuer: appConfig.mfa.otp.issuer,
            label: account,
            algorithm: "SHA1",
            digits: 6,
            period: 30,
            secret: otpsecret
        });

        qrcode.toDataURL(totp.toString(), (error, url) => {
            resolve(url)
        })
    })
}

export function validateOTPCode(account, otpsecret, token) {
    return new Promise((resolve, reject) => {
        let totp = new TOTP({
            issuer: appConfig.mfa.otp.issuer,
            label: account,
            algorithm: "SHA1",
            digits: 6,
            period: 30,
            secret: otpsecret
        });
        
        resolve(totp.validate({ token, window: 2 }));
    });
}

export async function saveOTPSecret(userid, otpsecret) {
    setOTPSecret(userid, otpsecret)
}