const moment = require('moment');

module.exports = {
    friendlyName: 'Verify reset code mobile',
    description: 'Vérifie le code de réinitialisation mobile (6 chiffres)',

    inputs: {
        username: {
            type: 'string',
            required: true
        },
        code: {
            type: 'string',
            required: true
        }
    },

    exits: {
        success: {},
        invalid: {
            description: 'Code invalide ou expiré',
            statusCode: 400
        },
        userNotFound: {
            description: 'Utilisateur non trouvé',
            statusCode: 404
        }
    },

    fn: async function ({ username, code }, exits) {
        try {
            const user = await Utilisateurs.findOne({
                login: username,
                desactiverCompte: false
            });
            if (!user) {
                return exits.userNotFound('Utilisateur non trouvé');
            }
            if (!user.resetToken || !user.resetTokenExpiresAt) {
                return exits.invalid('Aucune demande de code en cours');
            }
            if (user.resetToken !== code) {
                return exits.invalid('Code invalide');
            }
            if (moment().isAfter(moment(user.resetTokenExpiresAt))) {
                return exits.invalid('Code expiré');
            }
            // Log Activity
            const ouestDate = moment.utc(new Date()).utcOffset('+01:00');
            await ActivityLogs.create({
                date: ouestDate.format('YYYY-MM-DD'),
                heure: ouestDate.format('HH:mm:ss'),
                username: user.login,
                action: "VERIFY_RESET_CODE_MOBILE",
                status: "success",
                errorMessage: null,
                device: "Mobile"
            });
            return exits.success({ message: 'Code valide' });
        } catch (err) {
            await ActivityLogs.create({
                date: moment().format('YYYY-MM-DD'),
                heure: moment().format('HH:mm:ss'),
                username: username,
                action: "VERIFY_RESET_CODE_MOBILE",
                status: "failed",
                errorMessage: (typeof err === 'string' ? err : (err && err.message) || 'Erreur inconnue'),
                device: "Mobile"
            });
            return exits.invalid('Erreur lors de la vérification du code');
        }
    }
}; 