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

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

router.get('/', async (req, res, next) => {

    try {
        const users = await userController.getUsersList();
        return res.status(200).send(users);
    } catch(error) {
        next(error);
    }

});

router.put('/:user_id',
    body().custom(body => {
        const keys = ['email', 'displayName', 'disabled'];
        return Object.keys(body).every(key => keys.includes(key));
    }).withMessage('An invalid parameter was sent.'),
    async (req, res, next) => {

    const errors = validationResult(req);

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

    const user_id = req.params.user_id
    const user = req.body;

    try {
        const updatedUser = await userController.updateUser(user_id, user);
        return res.status(200).send(updatedUser);
    } catch(error) {
        next(error);
    }

});

router.delete('/:user_id', async (req, res, next) => {

    const user_id = req.params.user_id;

    try {
        await userController.deleteUser(user_id);
        return res.status(204).send();
    } catch(error) {
        next(error);
    }

});

module.exports = router;
