const { Service } = require('flitter-di')
const speakeasy = require('speakeasy')
const qrcode = require('qrcode')

class MFAService extends Service {
    static get services() {
        return [...super.services, 'configs']
    }

    secret(user) {
        return speakeasy.generateSecret({
            length: this.configs.get('auth.mfa.secret_length') ?? 20,
            name: `${this.configs.get('app.name')} (${user.uid.toLowerCase()})`,
        })
    }

    async qr_code(secret) {
        return new Promise((resolve, reject) => {
            qrcode.toDataURL(secret.otpauth_url, (err, image_data) => {
                if ( err ) reject(err)
                else resolve(image_data)
            })
        })
    }
}

module.exports = exports = MFAService
