const mailsend = require('../mail');
const validator = require('validator');
const utility = require('../utility');

async function RecorveryPassword(req, res) {
    try {
        if (!validator.isEmail(req.body)) {
            return res.status(400).json({
                mess: "Nieprawidłowy adress email",
                success: false
            });
        }

        const email = req.body;
        const emailContent = await PrepareMail(email);

        mailsend.SetMail(emailContent);
        if (await mailsend.SendMail()) {
            return res.status(400).json({
                mess: "Nieudało się wysłać emaila z linkiem resetującym",
                success: false
            });
        }

        res.status(200).json({
            mess: "Wysłano link do resetu hasła na adress email",
            success: true
        });
    }
    catch(e) {
        console.error(`Nie można zresetować hasła: ${e}`);
        res.status(500).json({
            mess: "Nie można zresetować hasła",
            success: false
        });
    }
}

async function PrepareMail(email) {
    const url = '';

    const to = 'noreply@server.net';
    const subject = 'Recorvery Password';

    const emailTemplate = '';

    const content = utility.ReplacePlaceholder({RECORVERY_URL: url}, emailTemplate);

    return {to: to, subject: subject, text: content};
}

module.exports = RecorveryPassword;