const {
    body,
    validationResult
} = require('express-validator');
const User = require('../models/User');
const validateEditAdmin = () => {
    return [
        body('first_name', 'This field is required!').trim().notEmpty()
        .matches(/^[A-Za-z]+$/)
        .withMessage('Name must be alphabetic.'),
        body('last_name', 'This field is required!').trim().notEmpty()
        .matches(/^[A-Za-z]+$/)
        .withMessage('Name must be alphabetic.'),
        body('email', 'This field is required!').trim().notEmpty()
        .isEmail().withMessage('Email is not valid')
        .custom((email, { req }) => {
            var old_email = req.body.old_email;
            if (email != old_email) {
                return User.findOne({
                    where: {
                        email: email
                    }
                })
                    .then(user => {
                        if (user) {
                            return Promise.reject('Email already in use');
                        }
                    })
            }
            return true;
        }),
        body('base_image', 'This field is required!').notEmpty(),
        body('phone', 'This field is required!').trim().notEmpty()
        .isNumeric()
        .withMessage('Only Number is Allowed'),
    ];
}
const validateEditAdm = (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/user/' + req.params.id)
    }
    return res.redirect('/admin/user')
}
module.exports = {
    validateEditAdmin,
    validateEditAdm
}