/**
 * @file usersController.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

const service = require('../services/usersServices');
const utility = require('../utility');

const getByID = (req, res) => {
    const id = Number(req.params.id);
    service.getByID(id).then((user) => {
        delete user.password;
        res.status(utility.getResStatus(user))
            .json(user);
    });
}

const patch = (req, res) => {
    const changes = req.body;
    if (Object.keys(changes).length === 0) {
        res.status(200).json({ message: "Nothing changed!" });
    }
    service.update(changes).then((user) => {
        delete user.password;
        res.status(utility.getResStatus(user))
            .json(user);
    });
}

const deleteByID = (req, res) => {
    const id = Number(req.params.id);
    service.deleteByID(id).then((user) => {
        delete user.password;
        res.status(utility.getResStatus(user))
            .json(user);
    });
}

const getByFilter = (req, res) => {
    const filter = {};
    filter.id = req.query.id;
    filter.email = req.query.email;
    filter.name = req.query.name;
    filter.role = req.query.role;
    const max_items = Number(req.query.max_items);
    const page = Number(req.query.page);
    service.getByFilter(filter, max_items || 20, page || 0).then((users) => {
        users.items = users?.items.map(user => {
            delete user.password;
            return user;
        });
        res.status(utility.getResStatus(users))
            .json(users);
    });
}

const getMe = (req, res) => {
    return res.status(200).json(req.user);
}

module.exports = {
    getByID,
    getMe,
    patch,
    deleteByID,
    getByFilter
}