const mysql = require("mysql2");

const saveQuizResponse = (req, res) => {
    const connection = mysql.createConnection({
        host: process.env.MARIA_HOST,
        user: process.env.MARIA_USER,
        password: process.env.MARIA_PASS,
        database: process.env.MARIA_DBNM
    });

    connection.connect((err) => {
        if (err) {
            console.error('Error connecting to the database:', err);
            res.status(500).send('Internal Server Error');
            return;
        }
        console.log('Connected to the MariaDB database.');
    });

    const data = req.body;
    // console.log(data);

    const query = `INSERT INTO quiz_response (questionId, quizId, selectedOption) VALUES (?, ?, ?)`;

    let errorOccurred = false;
    let promises = [];

    data.forEach((response) => {
        const values = [response.questionId, response.quizId, response.selectedOption];
        const promise = new Promise((resolve, reject) => {
            connection.query(query, values, (err, results) => {
                if (err) {
                    console.error('Error inserting data:', err);
                    errorOccurred = true;
                    reject(err);
                } else {
                    resolve(results);
                }
            });
        });
        promises.push(promise);
    });

    Promise.all(promises)
        .then(() => {
            if (!errorOccurred) {
                res.status(200).json({success: true, quizId: data[0].quizId, message: 'All responses saved successfully.' });
            }
        })
        .catch((error) => {
            console.error('Error saving responses:', error);
            res.status(500).send('Internal Server Error');
        })
        .finally(() => {
            connection.end();
        });
};

module.exports = saveQuizResponse;
