const db = require('../config/db');
const md5 = require('md5');

const getProfile = async (req, res) => {
    try {
        // Handle potential mismatch from legacy code (id_prov vs id_proveedor)
        const id_proveedor = req.body.id_proveedor || req.body.id_prov;

        if (!id_proveedor) {
            return res.status(400).json({ error: "Missing id_proveedor" });
        }

        const [rows] = await db.query(
            "SELECT nombre, num_proveedor, cp FROM m_proveedores WHERE id_proveedor = ?",
            [id_proveedor]
        );

        // PHP returned an array of objects
        return res.json(rows);
    } catch (error) {
        console.error("Error getting profile:", error);
        return res.status(500).json([]);
    }
};

const changePassword = async (req, res) => {
    try {
        const { usuario, password } = req.body;

        if (!usuario || !password) {
            return res.json("1"); // Error code
        }

        const hashedPassword = md5(password);

        const [result] = await db.query(
            "UPDATE m_proveedores_trasportistas SET password = ? WHERE dni = ?",
            [hashedPassword, usuario]
        );

        if (result.affectedRows > 0) {
            return res.json("0"); // Success code
        } else {
            // Could mean user not found or password didn't change, but legacy returns 0 for success.
            // If nothing updated, maybe user doesn't exist.
            // Legacy logic: if query runs, return 0. If error, return 1.
            // But checking affectedRows is safer.
            // Let's stick to legacy behavior: if no error, return 0? 
            // The PHP code only returns 1 if mysqli_query fails (returns false).
            return res.json("0"); 
        }
    } catch (error) {
        console.error("Error changing password:", error);
        return res.json("1");
    }
};

module.exports = {
    getProfile,
    changePassword
};
