const dbConnect = require('../configs/dbConnection.js');

exports.validateDevice = async (req, res) => {
    try {
        const { uid, mobile, device_hash, device_label } = req.body;

        // 🔹 1. Validate input
        if (!uid || !mobile || !device_hash || !device_label) {
            return res.status(400).json({ error: 'All fields are mandatory' });
        }

        // 🔹 2. Check user exists
        const [users] = await dbConnect.query(
            `SELECT uid FROM ulogin WHERE uid = ? AND umob = ?`,
            [uid, mobile]
        );

        if (users.length === 0) {
            return res.status(404).json({ status: 'user_not_found' });
        }

        // 🔥 3. Check device EXACT MATCH + ACTIVE
        const [devices] = await dbConnect.query(
            `SELECT is_active FROM user_devices 
             WHERE user_id = ? 
             AND device_hash = ? 
             AND device_label = ?`,
            [uid, device_hash, device_label]
        );

        if (devices.length === 0) {
            return res.status(200).json({ status: 'device_not_found' });
        }

        const device = devices[0];

        // 🔹 4. Return status
        if (device.is_active === 1) {
            return res.status(200).json({ status: 'active' });
        } else {
            return res.status(200).json({ status: 'inactive' });
        }

    } catch (error) {
        console.error('Error in validateDevice API:', error.message);
        return res.status(500).json({ error: 'Internal server error' });
    }
};