var db, transporter = require('../config/dbConfig');

const mailOptions = {
    from: 'your-email@example.com', // Replace with your email address
    to: 'recipient@example.com', // Replace with the recipient's email address
    subject: 'OTP to login',
    text: 'Body of the email'
};

exports.sendOtp = (req, res) => {
    const email = req.body.email;
    const otp = generateRandom4DigitNumber();

    db.query(
        'INSERT INTO email_otp (email, otp) VALUES (?, ?) ON DUPLICATE KEY UPDATE otp = ?',
        [email, otp, otp],
        (err, results) => {
            if (err) {
                console.error('Error executing query:', err);
                res.status(500).json({ success: false, message: 'Internal Server Error' });
                return;
            }
            sendMail(otp, email, req);
        }
    );

}

exports.validateOtp = async (req, res) => {
    const otp = req.body.otp;
    const email = req.body.email;
    const otpQuery = "SELECT * from email_otp where otp = ? and email = ?";
    const deleteOtpQuery = "DELETE from email_otp WHERE email = ?";
    db.query(otpQuery, [otp, email], (err, results) => {
        if (err) {
            console.error('Error executing query:', err);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
            return;
        }
        if (results.length > 0) {
            db.query(deleteOtpQuery, [email], (err, results) => {
                res.status(200).json({ success: true, message: 'Valid OTP' });
            })
        } else {
            // OTP is invalid
            res.status(400).json({ success: false, message: 'Invalid OTP' });
        }
    });
};

function sendMail(otp, email, req) {
    const mailOptions = {
        from: 'communityrule.app@medlab.host', // Replace with your email address
        to: email, // Replace with the recipient's email address
        subject: 'Login code for commnunityRule',
        text: 'Login code for CommunityRule: ' + otp,
    };
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            console.error('Error:', error);
            req.status(500).json({ success: false, message: 'Internal Server Error' });
            return;
        }
        res.json({ success: true, message: 'You must have received an email with otp successfully.' });
    });

}
function generateRandom4DigitNumber() {
    // Generate a random number between 1000 and 9999
    const random4DigitNumber = Math.floor(Math.random() * 9000) + 1000;
    return random4DigitNumber;
}