const {
    body,
    validationResult
} = require('express-validator');
const User = require('../models/User');
const validateLogin = () => {
    return [
        body('email', 'This field is required!').trim().notEmpty()
        .custom(email => {
            return User.findOne({
                where: {
                    email: email,
                    role_id: 1,
                    status: 1
                }
            })
                .then(user => {
                    if (!user) {
                        return Promise.reject('You are Unauthorized to Login Admin Panel');
                    }
                })
        }),

    ];
}
const validateLog = (req, res, next) => {
    const errors = validationResult(req)
    console.log("req", req.body)
    if (errors.isEmpty()) {
        return next()
    }
    const extractedErrors = []
    errors.array({ onlyFirstError: true }).map(err => extractedErrors.push({ [err.param]: err.msg }));
    
    console.log("extractedErrors=>>>>>>>>>>>>>>>>>", extractedErrors)
    req.flash('validationError', extractedErrors);
    req.flash('form', req.body);
    if (req.params.id) {
        return res.redirect('/admin/customer/' + req.params.id)
    }
    return res.redirect('/admin/customer')
}
module.exports = {
    validateLogin,
    validateLog
}