const {
    body,
    validationResult
} = require('express-validator');
const User = require('../models/User');
const validateCustomers = () => {
    console.log("here");
    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 => {
            return User.findOne({
                where: {
                    email: email
                }
            })
                .then(user => {
                    console.log("user", user)
                    if (user) {
                        return Promise.reject('Email already in use');
                    }
                })
        }),
        body('address1', 'This field is required!').trim().notEmpty(),
        // body('address2', 'This field is required!').trim().notEmpty(),
        body('phone', 'This field is required!').trim().notEmpty()
        .isNumeric()
        .withMessage('Only Number is Allowed'),
        body('zip', 'This field is required!').trim().notEmpty()
        .isNumeric().withMessage('Only Number is allowed'),
    ];
}
const validateCust = (req, res, next) => {
    const errors = validationResult(req)
    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 = {
    validateCustomers,
    validateCust
}