const userService = require('../services/userService');

exports.getUsers = async (req, res) => {
    try {
        const users = await userService.getAllUsers();
        res.json(users);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.createUser = async (req, res) => {
    try {
        const user = await userService.createUser(req.body, req.user.id);
        res.status(201).json(user);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.updateUser = async (req, res) => {
    try {
        const user = await userService.updateUser(req.params.id, req.body, req.user.id);
        res.json(user);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.toggleStatus = async (req, res) => {
    try {
        const user = await userService.toggleStatus(req.params.id, req.user.id);
        res.json(user);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.getRoles = async (req, res) => {
    try {
        const roles = await userService.getRoles();
        res.json(roles);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.deleteUser = async (req, res) => {
    try {
        await userService.deleteUser(req.params.id, req.user.id);
        res.json({ message: 'User deleted' });
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.resetPassword = async (req, res) => {
    try {
        const newPassword = await userService.resetUserPassword(req.params.id, req.user.id);
        res.json({ message: 'Password reset successfully', newPassword });
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.resendCredentials = async (req, res) => {
    try {
        const result = await userService.resendUserCredentials(req.params.id, req.user.id);
        res.json({ message: 'Credentials resent successfully', newPassword: result.newPassword });
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};
