const dbConnect = require('../configs/dbConnection.js');
const { verifyCaptcha } = require('../utils/verifyCaptcha.js');
const bcrypt = require('bcryptjs');

exports.login = async (req, res) => {
    try {
        const { mobile, password, captchaToken } = req.body;
        console.log(mobile);
        console.log(password);
        console.log(captchaToken);

        // Validate input
        if (!mobile || !password || !captchaToken) {
            return res.status(400).json({ error: 'All fields are mandatory' });
        }

        // 1️⃣ Verify Turnstile token first
        const captchaResponse = await verifyCaptcha(captchaToken);
        if (!captchaResponse.success) {
            return res.status(400).json({ error: 'Captcha verification failed' });
        }

        // 2️⃣ Check if user exists
        const [rows] = await dbConnect.query(
            `SELECT uid, uname, upass, umob, ubal, ucred, umail, uadd, ucity, ucrate, upin, uflag, did 
             FROM ulogin WHERE umob = ?`, 
            [mobile]
        );

        if (rows.length === 0) {
            return res.status(401).json({ error: 'You are not registered' });
        }

        const user = rows[0];

        // 3️⃣ Verify password
        const match = await bcrypt.compare(password, user.upass);
        if (!match) {
            return res.status(400).json({ error: 'Incorrect password' });
        }

        // 4️⃣ Successful login
        delete user.upass; // Remove password before sending response
        return res.status(200).json({ message: 'Login successful', user });

    } catch (error) {
        console.error('Error in signin API:', error.message);
        return res.status(500).json({ error: 'Failed to sign in' });
    }
};
