const {
    body,
    validationResult
} = require('express-validator');
const User = require('../models/User');
const validateEditDriver = () => {
    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('driver_image_base64', 'This field is required!').notEmpty(),
        body('driver_licence_base64', 'This field is required!').notEmpty(),
        body('driver_rc_base64', 'This field is required!').notEmpty(),
        body('password').trim().custom((password, { req }) => {
            if (password !== "") {
                if (password.length < 8) {
                    return Promise.reject('Password must be greater than 8 characters');
                }
            }
            return true;
        }),
        body('confirm_password').trim()
            .custom(async (confirmPassword, { req }) => {
                const password = req.body.password
                if (password !== "") {
                    if (password !== confirmPassword) {
                        return Promise.reject('Password must be same');
                    }
                }
                return true;
            }),
        body('phone', 'This field is required!').trim().notEmpty()
            .isNumeric()
            .withMessage('Phone is not valid'),
        body('address', 'This field is required!').trim().notEmpty()
    ];
}
const validateEditDriv = (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/driver/' + req.params.id)
    }
    return res.redirect('/admin/driver')
}
module.exports = {
    validateEditDriver,
    validateEditDriv
}