
let moment = require('moment');

module.exports = {


    friendlyName: 'Login',


    description: 'Login auth.',


    inputs: {
        username: {
            type: 'string',
            require: true
        },
        codeVerif: {
            type: 'string',
            require: true
        },

    },


    exits: {
        notFound: {
            description: 'User not found',
            statusCode: 404
        },
        encryptionError: {
            statusCode: 500
        }
    },


    fn: async function ({ username, codeVerif }, exits) {
        let ouestDate = moment.utc(new Date()).utcOffset('+01:00');
        let date = ouestDate.format('YYYY-MM-DD');
        let heure = ouestDate.format('HH:mm:ss');
        try {
            if (username === '' || codeVerif === '') {
                await ActivityLogs.create({
                    date,
                    heure,
                    username,
                    action: "VERIFY_CODEVERIF",
                    status: "failed",
                    errorMessage: "Champs manquants",
                    device: "Web"
                });
                return exits.notFound('Veuillez renseigner tous les champs')
            }
            let user;
            user = await Utilisateurs.find({ login: username, codeVerif: codeVerif, desactiverCompte: false },).then(_.first)
            if (!user) {
                await ActivityLogs.create({
                    date,
                    heure,
                    username,
                    action: "VERIFY_CODEVERIF",
                    status: "failed",
                    errorMessage: "Code verification incorrect",
                    device: "Web"
                });
                return exits.notFound('Code verification incorrect')
            }
            if (user) {
                await ActivityLogs.create({
                    date,
                    heure,
                    username: user.login,
                    action: "VERIFY_CODEVERIF",
                    status: "success",
                    errorMessage: null,
                    device: "Web"
                });
                let resp = true
                return exits.success(resp)
            }
        } catch (err) {
            await ActivityLogs.create({
                date,
                heure,
                username,
                action: "VERIFY_CODEVERIF",
                status: "failed",
                errorMessage: (typeof err === 'string' ? err : (err && err.message) || 'Erreur inconnue'),
                device: "Web"
            });
            return exits.error('Erreur lors de la vérification du code.');
        }
    }


};
