const { body, validationResult } = require('express-validator');
const express = require('express');
const router = express.Router();

const userController = require('../controllers/user.controller');

router.post('/create',
    body('name').notEmpty().withMessage('name field must not be empty.'),
    body('email').isEmail().withMessage('email field must be a valid email.'),
    body('password').isLength({ min: 6 }).withMessage('password must have at least 6 characters.'),
    body('role').isIn(['admin', 'user']).withMessage('role must be of type admin or user.'),
    async (req, res, next) => {

    const user = req.body;
    const errors = validationResult(req);

    if(!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

    try {

       const userRecord = await userController.createUser(user);

       if(userRecord) {
           await userController.setUserRole(userRecord.uid, user.role);
           await userController.sendUserCredentials(user.email, user.password);
           return res.status(200).send();
       } else {
           return res.status(500).send({ error: "Failed to create user. "});
       }

    } catch(error) {
        return res.status(500).send({error: error.errorInfo.message});
    }

});

module.exports = router;
