const { getUserById, updateUser } = require('../services/user.service');
const { logAudit } = require('../services/audit.service');

/**
 * Liefert die Rollen eines Benutzers
 * @param {Object} req - Express Request Objekt
 * @param {Object} res - Express Response Objekt
 */
exports.getUserRoles = async (req, res) => {
  try {
    const { userId } = req.params;
    
    const user = await getUserById(userId);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
    
    res.json(user.roles || []);
  } catch (error) {
    console.error('Error getting user roles:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

/**
 * Ändert die Rollen eines Benutzers
 * @param {Object} req - Express Request Objekt
 * @param {Object} res - Express Response Objekt
 */
exports.updateUserRoles = async (req, res) => {
  try {
    const { userId } = req.params;
    const { roles } = req.body;
    
    // Validierung der Rollen
    if (!Array.isArray(roles)) {
      return res.status(400).json({ error: 'Roles must be an array' });
    }
    
    // Überprüfe, ob alle Rollen gültig sind
    const validRoles = ['user', 'moderator', 'admin'];
    for (const role of roles) {
      if (!validRoles.includes(role)) {
        return res.status(400).json({ error: `Invalid role: ${role}` });
      }
    }
    
    const user = await getUserById(userId);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
    
    // Aktualisiere die Rollen
    user.roles = roles;
    await updateUser(userId, { roles });
    
    // Audit-Eintrag
    await logAudit({
      actorUserId: req.user?.id || 'system',
      action: 'USER_ROLES_UPDATE',
      targetType: 'user',
      targetId: userId,
      details: { oldRoles: user.roles, newRoles: roles }
    });
    
    res.json({ message: 'Roles updated successfully' });
  } catch (error) {
    console.error('Error updating user roles:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

/**
 * Entfernt alle Rollen eines Benutzers
 * @param {Object} req - Express Request Objekt
 * @param {Object} res - Express Response Objekt
 */
exports.deleteUserRoles = async (req, res) => {
  try {
    const { userId } = req.params;
    
    const user = await getUserById(userId);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
    
    // Entferne alle Rollen
    user.roles = [];
    await updateUser(userId, { roles: [] });
    
    // Audit-Eintrag
    await logAudit({
      actorUserId: req.user?.id || 'system',
      action: 'USER_ROLES_DELETE',
      targetType: 'user',
      targetId: userId,
      details: { oldRoles: user.roles, newRoles: [] }
    });
    
    res.json({ message: 'Roles deleted successfully' });
  } catch (error) {
    console.error('Error deleting user roles:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};