const dbConnect = require('../configs/dbConnection.js');
const {sendOtp, verifyOtp} = require('../../smsapi/model/smsModel.js');
// const {verifyCaptcha} = require('../utils/verifyCaptcha.js');
const bcrypt = require('bcryptjs');

exports.CheckUser = async (req, res) => {
    try {
        const {email, mobile} = req.body;
        console.log(req.body);
    //  const remoteIp = req.ip;
    //  console.log(user, email, mobile, password, recaptch);
    //  const captchaResponse = verifyCaptcha(token, remoteIp.ip)

    //  if (!captchaResponse.success) {
    //   return res.status(400).json({error:'captcha verification failed'})
    //  }
      
     console.log("mobile:", mobile, "email:", email);

        // Check for user in database
    
        if (!mobile || !email) {
            return res.status(400).json({ error: 'all fields are mandatory' });
        }
        
        const [users] = await dbConnect.query(`SELECT umob, umail FROM ulogin WHERE umob=? AND umail=?`,
        [mobile.trim(), email.trim()]
        );
        
         console.log(users);
      
        if (!users || users.length === 0) {
            console.log("user not found");
            return res.status(404).json({ error: 'User not registered' });
        }
        
        console.log(users);
        
        // Format and sanitize mobile number
        const trimmedMobileNo = mobile.trim().replace(/\D/g, '').replace(/^0|^91/, '');
        const formattedMobileNo = '+91' + trimmedMobileNo;
        const trimmedemailId = email.trim();
        console.log(formattedMobileNo, trimmedemailId);
        // send otp for verificaton
        let sendSmsResponse  = await sendOtp(formattedMobileNo, 'BOBROSOTP');
        
        console.log(sendSmsResponse);
        if (!sendSmsResponse) {
            return res.status(500).json({ error: 'OTP sending failed' });
        }
        res.status(200).json({sendSmsResponse});
        
    } catch (error) {
        // console.error('Error:', error.message);
        res.status(500).json({ error:  error.message });
    }
};

exports.changePassword = async (req, res) => {
    try{
        const {mobile, otp, newPassword, confirmPassword} = req.body;
        
        const verifyOtpResponse = await verifyOtp(mobile, otp);
        // console.log("verifyOtpResponse:", verifyOtpResponse );
        // console.log("verifyOtpResponse:", verifyOtpResponse.Details );
        
        if (verifyOtpResponse.Details === "OTP Mismatch") {
            // console.log("verifyOtpResponseFor Check:", verifyOtpResponse.Details );
            return res.status(404). json({error: 'otp verfication failed'});
        };

        //check if password matches with previous 3 passwords  
        
        const [rows] =  await dbConnect.query(`SELECT upass, lastpwd1, lastpwd2 FROM ulogin WHERE uuser = ?`,
        [mobile]
        );
        
        // console.log(rows);
        
        // Check if rows[0] exists to avoid runtime error if user not found
        if (!rows || rows.length === 0) {
        // console.log("User not found.");
        res.status(404).json({ error: "User not found."});;
        }
        
        const previousPasswords = rows[0];
        
       const previousHashes = [
    previousPasswords.upass ?? '',
    previousPasswords.lastpwd1 ?? '',
    previousPasswords.lastpwd2 ?? ''
];

for (let hash of previousHashes) {
    if (hash && await bcrypt.compare(newPassword, hash)) {
        return res.status(400).json({
            msg: 'OTP verified successfully but please note that the new password must not be one of the last three passwords you have used.'
        });
    }
}


        
        await dbConnect.query(`UPDATE ulogin SET lastpwd2 = lastpwd1, lastpwd1 = upass WHERE  uuser = ?`,
        [mobile]
        );
        
        const hashedPassword = await bcrypt.hash(newPassword, 10,);
        
        await dbConnect.query(`UPDATE ulogin SET upass = ?, pwdchangedate = ? WHERE  uuser = ?`,
        [hashedPassword, new Date(), mobile]
        );

        return res.status(200).json({msg: 'Password has been reset successfully'})
    } catch (error) {
        // console.error('Error:', error.message);
        res.status(500).json({ error: "Something went wrong. Please try again later"  });
    }
};
