// SI DATE LIMITE D'INSCRIPTION DÉPASSÉE ON vérifie que le code secret est bien ok

/////////////////////////////////////////////////
// APPELS DES MODULES
/////////////////////////////////////////////////
const path = require("path");

/////////////////////////////////////////////////
// APPELS DES MODULES PERSOS
/////////////////////////////////////////////////
// loggings
const logger = require("../public/js/app/logger_stagenat");
// DB
const { connect_DB_promise } = require('../modules/db/databaseconnect');

////////////////////////////////////////////////////
// FILE NAME
////////////////////////////////////////////////////
const filename = path.parse(__filename).base;

async function verif_codesecret(req, res) {
    logger.info("/// DÉBUT FONCTION verif_codesecret", { numsession: req.session.id, label: filename});
    //Connexion
    let db_connection_promise = await connect_DB_promise();
    if (req.session.datelimitedepass === "oui") {
        logger.info("DATE LIMITE DEPASSÉE", { numsession: req.session.id, label: filename});
        // Query
        let sql_codesecret = 'select code, statut from code where code = "' + req.session.code_secret + '" AND statut = "actif"';
        logger.info("sql_codesecret  : " + sql_codesecret, { numsession: req.session.id, label: filename});
        const [results_codesecret, fields] = await db_connection_promise.execute(sql_codesecret);
        await db_connection_promise.end();
        logger.info("results_codesecret.length  : " + results_codesecret.length, { numsession: req.session.id, label: filename});
        if (results_codesecret.length) {
            // on peut continuer
            req.session.onpeutcontinuer = "oui"

        } else {
            // CODE SECRET ERRONÉ
            req.session.onpeutcontinuer = "non"
            logger.info("Code secret erroné : "+req.session.code_secret, { numsession: req.session.id, label: filename});
            // ON AFFICHE LA PAGE DE SAISIE DE L'IDENTIFIANT AVEC ERREUR "déjà inscrit"
            req.session.err_mail_form_adhesion_1 = "Le code inscription <strong>" + req.session.code_secret + "</strong> est erroné.";
            //res.redirect('/stagenational/identifier');
        }
    } else {
        // on peut continuer
        req.session.onpeutcontinuer = "oui"
    }
    logger.info("/// FIN FONCTION verif_codesecret", { numsession: req.session.id, label: filename});
}

module.exports = {
    verif_codesecret
}