const API = require("../../lib/API")
const { BaseStdResponse } = require("../../BaseStdResponse")
const Redis = require('../../plugin/DataBase/Redis')
const EmailTemplate = require('../../plugin/Email/emailTemplate')

// 发送邮箱验证码
class SendEmail extends API {
    constructor() {
        super()

        this.setMethod("POST")
        this.setPath("/Captcha/SendEmail")
    }

    async onRequest(req, res) {
        const { email, text, id, type } = req.body

        if ([email, text, id, type].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 1513126
            })
            
        try {
            const code = await Redis.get(`captcha:${id}`)
            if (!code || code != text.toLowerCase())
                return res.json({
                    ...BaseStdResponse.SMS_CHECK_FAIL,
                    msg: '验证码输入错误或已过期'
                })

            await Redis.del(`captcha:${id}`)
        } catch (err) {
            this.logger.error(`验证图片验证码失败！${err.stack}`)
            return res.json({
                ...BaseStdResponse.DATABASE_ERR,
                msg: '验证失败！'
            })
        }

        const code = Math.random().toFixed(6).slice(-6)
        try {
            await Redis.set(`email:${email}`, code, {
                EX: 600
            })
        } catch (err) {
            this.logger.error(`发送邮箱验证码失败！${err.stack}`)
            return res.json({
                ...BaseStdResponse.SMS_SEND_FAIL,
                msg: '请检查邮箱格式后再试！'
            })
        }

        res.json({
            ...BaseStdResponse.OK
        })

        // 先返回后发送
        EmailTemplate.checkEmail(email, code)
    }
}

module.exports.SendEmail = SendEmail
