const Lead = require('../models/leadModel');
const {contactFormSchema, quFormSchema} = require("./validations");
const {recaptchaVerify} = require("./recaptchaVerify");
const {sendSimpleMail} = require("../helpers/sendSimpleMail");

const simple_lead = async (req, res) => {
    const {body} = req
    const {error} = contactFormSchema.validate(body)
    if (error) {
        res.status(400).json(error)
        return
    }
    const {name, email, phone, message, recaptcha_token} = body
    const recaptchaScore = await recaptchaVerify(recaptcha_token)
    let leadObj = new Lead
    try {
        await leadObj.insertLead(email, phone, name, message, recaptchaScore);
        leadObj.sendMail(name, email, phone, message).then()
        res.json({ok: true})
    } catch (e) {
        console.log('Error in simple_lead', e)
        res.status(400).json({ok: false})
    }
}

const qualif_lead = async (req, res) => {
    const {body} = req
    const {error} = quFormSchema.validate(body)
    if (error) {
        res.status(400).json(error)
        return
    }
    const {quName, quId, quAns, recaptcha_token} = body
    const recaptchaScore = await recaptchaVerify(recaptcha_token)
    let leadObj = new Lead;

    let name = `qu_${quName}`
    if (['name', 'email', 'phone'].includes(quName))
        name = quName

    if (quName === "finish") {
        res.json({ok: true})
        return
    }

    if (quName === 'phone') {
        try {
            leadObj.sendMailQualification(leadObj.validateIdHash(quId)).then()
        } catch (e) {
            console.log('qualif_lead sendMail error', e)
        }
    }

    if (!quId || quId === 'undefined') {
        try {
            const idHash = await leadObj.insertQualification(name, quAns, recaptchaScore)
            res.send(idHash)
        } catch (e) {
            console.log('insertQualification error', e)
            res.status(400).send({ok: false})
        }
        return
    }

    try {
        await leadObj.updateQualification(quId, name, quAns)
        res.json({ok:true})
    } catch (e) {
        console.log('updateQualification error', e)
        res.status(400).send({ok: false})
    }
}

module.exports = {
    simple_lead,
    qualif_lead,
}