const mysql = require("mysql2");

const resultAfterQuizSubmit = (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 queryData = req.query;
    const responseValues = [queryData.id]; // Ensure this is an array

    const responseQuery = `SELECT * FROM quiz_response WHERE quizId = ?`;
    connection.query(responseQuery, responseValues, (err, results) => {
        if (err) {
            console.error('Error retrieving data:', err);
            res.status(500).send('Internal Server Error');
            connection.end();
            return;
        }

        let questionsProcessed = 0;
        let allResults = [];

        results.forEach((resultData, index) => {
            const questionId = [resultData.questionId]; // Ensure this is an array
            const answerQuery = `SELECT * FROM quiz_questions WHERE questionId = ?`;

            connection.query(answerQuery, questionId, (err, questionResults) => {
                if (err) {
                    console.error('Error retrieving question data:', err);
                    res.status(500).send('Internal Server Error');
                    connection.end();
                    return;
                }

                allResults.push({
                    response: resultData,
                    question: questionResults[0] // Assuming it returns one result per questionId
                });

                questionsProcessed++;

                if (questionsProcessed === results.length) {
                    let correctAnswers = 0;
                    allResults.forEach(item => {
                        if (item.response.selectedOption === item.question.correctAnswer) {
                            correctAnswers++;
                        }
                    });

                    let quizMessage;

                    if(correctAnswers > 3){
                        quizMessage = 'Congratulations on your achievement.'
                    }else if(correctAnswers < 3){
                        quizMessage = 'You not paassed the quiz Try Again'
                    }

                    res.status(200).json({
                        totalQuestions: results.length,
                        correctAnswers: correctAnswers,
                        message: quizMessage,
                        details: allResults
                    });

                    connection.end();
                }
            });
        });

        if (results.length === 0) {
            res.status(200).json({
                totalQuestions: 0,
                correctAnswers: 0,
                details: []
            });
            connection.end();
        }
    });
};

module.exports = resultAfterQuizSubmit;
