const { validationResult } = require('express-validator');
const db = require('../models')
const VariableModel = db.variable;

const save = async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        // Renvoyer les erreurs de validation au client
        return res.render('pages/setting/variable', { errors: errors.array() });
    }
    
    // Les données du formulaire sont valides
    // Récupérer les valeurs des champs
    const { variable, value } = req.body;
    let variableSaved = await VariableModel.create({variable, value});
    
    // Renvoyer une réponse réussie
    return res.status(200).json(variableSaved);
};

const findOneByName = async ( variable ) => {
    try {
        const variableReturned = await VariableModel.findOne({
          where: { variable }          
        });
        return variableReturned;
      } catch (error) {
        console.error('Error finding latest leave:', error);
        throw error;
      }
}

const getVacationPerMonth = async ( ) => {
    try{  
  
        let result = await VariableModel.findOne({
            where: { variable: 'vacation per month' }          
          });
        return result.value;
    } catch( err ) {
        console.log(err)
    }
}

const test = ( ) => {
    console.log('fasdkfhaiowejocaisdfjkanskdkadhfah vkajkfiajefinj3y48u9euf 3982u39ewucjvjqwoedj;OWEOWEHUIDHASDUKFH 3EU8FUEIRUOUD93U94U394793HIEHFUIASDFASHIDFAISLDHFUADBVMZCBXVJHAHSJDHKhkdfksdfiIIFHKHskjljkdjfKJKLDJFKfdiqrehficnKHIFAKDSJFKJEIRJKLJL')
  }
module.exports = {
    save,
    test,
    findOneByName,
    getVacationPerMonth
}