import permissionService from '../services/permissionService.js';

/**
 * Get user's permissions for a club
 */
export const getUserPermissions = async (req, res) => {
  try {
    const { clubId } = req.params;
    const userId = req.user.id;

    // Validierung: clubId muss eine gültige Zahl sein
    const parsedClubId = parseInt(clubId, 10);
    if (isNaN(parsedClubId) || parsedClubId <= 0) {
      return res.status(400).json({ error: 'Ungültige Club-ID' });
    }

    const permissions = await permissionService.getUserClubPermissions(userId, parsedClubId);

    if (!permissions) {
      return res.status(404).json({ error: 'Keine Berechtigungen gefunden' });
    }

    res.json(permissions);
  } catch (error) {
    console.error('Error getting user permissions:', error);
    res.status(500).json({ error: 'Fehler beim Abrufen der Berechtigungen' });
  }
};

/**
 * Get all club members with their permissions
 */
export const getClubMembersWithPermissions = async (req, res) => {
  try {
    const { clubId } = req.params;
    const userId = req.user.id;

    const members = await permissionService.getClubMembersWithPermissions(
      parseInt(clubId),
      userId
    );

    res.json(members);
  } catch (error) {
    console.error('Error getting club members with permissions:', error);
    if (error.message === 'Keine Berechtigung zum Anzeigen von Berechtigungen') {
      return res.status(403).json({ error: error.message });
    }
    res.status(500).json({ error: 'Fehler beim Abrufen der Mitglieder' });
  }
};

/**
 * Update user role
 */
export const updateUserRole = async (req, res) => {
  try {
    const { clubId, userId: targetUserId } = req.params;
    const { role } = req.body;
    const updatingUserId = req.user.id;

    const result = await permissionService.setUserRole(
      parseInt(targetUserId),
      parseInt(clubId),
      role,
      updatingUserId
    );

    res.json(result);
  } catch (error) {
    console.error('Error updating user role:', error);
    if (error.message && error.message.toLowerCase().includes('keine berechtigung')) {
      return res.status(403).json({ error: error.message });
    }
    res.status(400).json({ error: error.message });
  }
};

export const updateUserRoles = async (req, res) => {
  try {
    const { clubId, userId: targetUserId } = req.params;
    const { roleIds } = req.body;
    const updatingUserId = req.user.id;

    const result = await permissionService.setUserRoles(
      parseInt(targetUserId),
      parseInt(clubId),
      Array.isArray(roleIds) ? roleIds : [],
      updatingUserId
    );

    res.json(result);
  } catch (error) {
    console.error('Error updating user roles:', error);
    if (error.message && error.message.toLowerCase().includes('keine berechtigung')) {
      return res.status(403).json({ error: error.message });
    }
    res.status(400).json({ error: error.message });
  }
};

/**
 * Update user custom permissions
 */
export const updateUserPermissions = async (req, res) => {
  try {
    const { clubId, userId: targetUserId } = req.params;
    const { permissions } = req.body;
    const updatingUserId = req.user.id;

    const result = await permissionService.setCustomPermissions(
      parseInt(targetUserId),
      parseInt(clubId),
      permissions,
      updatingUserId
    );

    res.json(result);
  } catch (error) {
    console.error('Error updating user permissions:', error);
    if (error.message && error.message.toLowerCase().includes('keine berechtigung')) {
      return res.status(403).json({ error: error.message });
    }
    res.status(400).json({ error: error.message });
  }
};

/**
 * Get available roles
 */
export const getAvailableRoles = async (req, res) => {
  try {
    const roles = permissionService.getAvailableRoles();
    res.json(roles);
  } catch (error) {
    console.error('Error getting available roles:', error);
    res.status(500).json({ error: 'Fehler beim Abrufen der Rollen' });
  }
};

/**
 * Get permission structure
 */
export const getPermissionStructure = async (req, res) => {
  try {
    const structure = permissionService.getPermissionStructure();
    res.json(structure);
  } catch (error) {
    console.error('Error getting permission structure:', error);
    res.status(500).json({ error: 'Fehler beim Abrufen der Berechtigungsstruktur' });
  }
};

export const getClubRoles = async (req, res) => {
  try {
    const { clubId } = req.params;
    const roles = await permissionService.getClubRoles(parseInt(clubId, 10), req.user.id);
    res.json(roles);
  } catch (error) {
    console.error('Error getting club roles:', error);
    if (error.message && error.message.toLowerCase().includes('keine berechtigung')) {
      return res.status(403).json({ error: error.message });
    }
    res.status(400).json({ error: error.message });
  }
};

export const createClubRole = async (req, res) => {
  try {
    const { clubId } = req.params;
    const role = await permissionService.createClubRole(parseInt(clubId, 10), req.body || {}, req.user.id);
    res.status(201).json(role);
  } catch (error) {
    console.error('Error creating club role:', error);
    if (error.message && error.message.toLowerCase().includes('keine berechtigung')) {
      return res.status(403).json({ error: error.message });
    }
    res.status(400).json({ error: error.message });
  }
};

export const updateClubRole = async (req, res) => {
  try {
    const { clubId, roleId } = req.params;
    const role = await permissionService.updateClubRole(parseInt(clubId, 10), parseInt(roleId, 10), req.body || {}, req.user.id);
    res.json(role);
  } catch (error) {
    console.error('Error updating club role:', error);
    if (error.message && error.message.toLowerCase().includes('keine berechtigung')) {
      return res.status(403).json({ error: error.message });
    }
    res.status(400).json({ error: error.message });
  }
};

export const deleteClubRole = async (req, res) => {
  try {
    const { clubId, roleId } = req.params;
    const result = await permissionService.deleteClubRole(parseInt(clubId, 10), parseInt(roleId, 10), req.user.id);
    res.json(result);
  } catch (error) {
    console.error('Error deleting club role:', error);
    if (error.message && error.message.toLowerCase().includes('keine berechtigung')) {
      return res.status(403).json({ error: error.message });
    }
    res.status(400).json({ error: error.message });
  }
};

/**
 * Update user status (activate/deactivate)
 */
export const updateUserStatus = async (req, res) => {
  try {
    const { clubId, userId: targetUserId } = req.params;
    const { approved } = req.body;
    const updatingUserId = req.user.id;

    const result = await permissionService.setUserStatus(
      parseInt(targetUserId),
      parseInt(clubId),
      approved,
      updatingUserId
    );

    res.json(result);
  } catch (error) {
    console.error('Error updating user status:', error);
    if (error.message && error.message.toLowerCase().includes('keine berechtigung')) {
      return res.status(403).json({ error: error.message });
    }
    res.status(400).json({ error: error.message });
  }
};

export default {
  getUserPermissions,
  getClubMembersWithPermissions,
  updateUserRole,
  updateUserRoles,
  updateUserPermissions,
  updateUserStatus,
  getAvailableRoles,
  getPermissionStructure,
  getClubRoles,
  createClubRole,
  updateClubRole,
  deleteClubRole,
};

