const express = require('express');
const router = express.Router();
const { executeQuery } = require('../config/database');
const { authenticateToken, requireMainAdmin, requireCompanyAdmin } = require('../middleware/auth');
const { validateId, handleValidationErrors } = require('../middleware/validation');

// Get all permission levels
router.get('/levels', authenticateToken, async (req, res) => {
  try {
    const permissionLevels = [
      { id: 3, name: 'main_admin', description: 'Full system access' },
      { id: 2, name: 'admin', description: 'Full project and user management access' },
      { id: 1, name: 'user', description: 'View-only access to assigned work' }
    ];
    
    res.json(permissionLevels);
  } catch (error) {
    console.error('Error fetching permission levels:', error);
    res.status(500).json({ message: 'Failed to fetch permission levels' });
  }
});

// Get user permissions
router.get('/user/:userId', authenticateToken, validateId('userId'), handleValidationErrors, async (req, res) => {
  try {
    const userId = req.params.userId;
    
    // Users can only view their own permissions unless they are admins
    if (
      req.user.id !== parseInt(userId, 10) &&
      req.user.role !== 'main_admin' &&
      req.user.role !== 'admin'
    ) {
      return res.status(403).json({ message: 'You do not have permission to view this user\'s permissions' });
    }

    // Get user's role and permission level
    const userQuery = `
      SELECT 
        u.id, 
        u.username,
        u.role, 
        u.permission_level,
        c.name as company_name
      FROM users u
      LEFT JOIN companies c ON u.company_id = c.id
      WHERE u.id = ?
    `;
    
    const user = await executeQuery(userQuery, [userId]);
    
    if (user.length === 0) {
      return res.status(404).json({ message: 'User not found' });
    }

    // Get permissions based on role
    let permissions = [];
    
    switch (user[0].role) {
      case 'main_admin':
        permissions = [
          'manage_companies',
          'manage_all_users',
          'manage_all_projects',
          'manage_all_tasks',
          'view_all_statistics'
        ];
        break;
      case 'user':
        permissions = [
          'manage_assigned_tasks',
          'view_own_statistics'
        ];
        break;
      case 'admin':
        permissions = [
          'manage_all_users',
          'manage_all_projects',
          'manage_all_tasks',
          'view_all_statistics'
        ];
        break;
    }

    res.json({
      user_id: user[0].id,
      username: user[0].username,
      role: user[0].role,
      permission_level: user[0].permission_level,
      company_name: user[0].company_name,
      permissions
    });
  } catch (error) {
    console.error('Error fetching user permissions:', error);
    res.status(500).json({ message: 'Failed to fetch user permissions' });
  }
});

// Update user permission level (Admin only)
router.put('/user/:userId', authenticateToken, requireCompanyAdmin, validateId('userId'), handleValidationErrors, async (req, res) => {
  try {
    const userId = req.params.userId;
    const { role, permission_level } = req.body;
    
    if (!role && !permission_level) {
      return res.status(400).json({ message: 'Role or permission level is required' });
    }

    // Get current user data
    const userQuery = 'SELECT role, permission_level, company_id FROM users WHERE id = ?';
    const user = await executeQuery(userQuery, [userId]);
    
    if (user.length === 0) {
      return res.status(404).json({ message: 'User not found' });
    }
    
    // Only main_admin can create/modify other main_admin or admin accounts
    if (
      (role === 'main_admin' || (user[0].role === 'main_admin' && role)) &&
      req.user.role !== 'main_admin'
    ) {
      return res.status(403).json({ message: 'Only main admins can manage main admin accounts' });
    }

    if (
      (role === 'admin' || (user[0].role === 'admin' && role)) &&
      req.user.role !== 'main_admin'
    ) {
      return res.status(403).json({ message: 'Only main admins can manage admin accounts' });
    }

    // Validate permission level
    if (permission_level && (permission_level < 1 || permission_level > 3)) {
      return res.status(400).json({ message: 'Invalid permission level. Must be between 1 and 3' });
    }
    
    // Map role to permission level if only role is provided
    let newPermissionLevel = permission_level;
    if (role && !permission_level) {
      switch (role) {
        case 'main_admin':
          newPermissionLevel = 3;
          break;
        case 'admin':
          newPermissionLevel = 2;
          break;
        case 'user':
        default:
          newPermissionLevel = 1;
          break;
      }
    }
    
    // Map permission level to role if only permission level is provided
    let newRole = role;
    if (permission_level && !role) {
      switch (permission_level) {
        case 3:
          newRole = 'main_admin';
          break;
        case 2:
          newRole = 'admin';
          break;
        case 1:
        default:
          newRole = 'user';
          break;
      }
    }

    // Update user role and permission level
    const shouldUpdateRole = Boolean(role) || (permission_level && !role);

    const updateQuery = `
      UPDATE users
      SET 
        ${shouldUpdateRole ? 'role = ?,' : ''} 
        ${permission_level ? 'permission_level = ?,' : ''} 
        updated_at = NOW()
      WHERE id = ?
    `;
    
    const queryParams = [];
    if (shouldUpdateRole) queryParams.push(newRole);
    if (permission_level) queryParams.push(newPermissionLevel);
    queryParams.push(userId);
    
    await executeQuery(updateQuery, queryParams);
    
    // Get updated user data
    const updatedUser = await executeQuery(`
      SELECT 
        u.id, 
        u.username,
        u.role, 
        u.permission_level,
        c.name as company_name
      FROM users u
      LEFT JOIN companies c ON u.company_id = c.id
      WHERE u.id = ?
    `, [userId]);

    res.json({
      message: 'User permissions updated successfully',
      user: updatedUser[0]
    });
  } catch (error) {
    console.error('Error updating user permissions:', error);
    res.status(500).json({ message: 'Failed to update user permissions' });
  }
});

// Get role hierarchy
router.get('/roles/hierarchy', authenticateToken, async (req, res) => {
  try {
    const roleHierarchy = {
      main_admin: {
        level: 3,
        can_manage: ['main_admin', 'admin', 'user']
      },
      admin: {
        level: 2,
        can_manage: ['user']
      },
      user: {
        level: 1,
        can_manage: []
      }
    };
    
    res.json(roleHierarchy);
  } catch (error) {
    console.error('Error fetching role hierarchy:', error);
    res.status(500).json({ message: 'Failed to fetch role hierarchy' });
  }
});

module.exports = router;
