/**
 * User Management Controllers
 * Request handlers for user management endpoints
 */

// Import user service
const userService = require('../services');
// Import async handler wrapper
const asyncHandler = require('../../../middlewares/asyncHandler');
// Import logger for logging
const logger = require('../../../utils/logger');
// Import SystemLog model for audit trail
const { SystemLog } = require('../../../models');

/**
 * Create user controller
 * Handles user creation
 * POST /api/users
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const createUser = asyncHandler(async (req, res) => {
  // Extract user data from request body
  const userData = req.body;
  
  // Call user service to create user
  const user = await userService.createUser(userData);
  
  // Log user creation to system logs
  await SystemLog.create({
    user_id: req.user.id, // Current user ID (from auth middleware)
    action: 'CREATE_USER', // Action type
    entity: 'User', // Entity type
    entity_id: user.id, // Created user ID
    payload: { username: user.username, role: user.role }, // Log payload
  });
  
  // Log user creation
  logger.info(`User created: ${user.username}`, {
    createdBy: req.user.id,
    userId: user.id,
    role: user.role,
  });
  
  // Return success response with created user data
  return res.status(201).json({
    success: true, // Indicate success
    message: 'User created successfully', // Success message
    data: { user }, // Created user data
  });
});

/**
 * Get user by ID controller
 * Handles retrieving a single user by ID
 * GET /api/users/:id
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getUserById = asyncHandler(async (req, res) => {
  // Extract user ID from request parameters
  const userId = parseInt(req.params.id);
  
  // Call user service to get user by ID
  const user = await userService.getUserById(userId);
  
  // Return success response with user data
  return res.status(200).json({
    success: true, // Indicate success
    message: 'User retrieved successfully', // Success message
    data: { user }, // User data
  });
});

/**
 * Update user controller
 * Handles user updates
 * PUT /api/users/:id
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const updateUser = asyncHandler(async (req, res) => {
  // Extract user ID from request parameters
  const userId = parseInt(req.params.id);
  // Extract update data from request body
  const updateData = req.body;
  
  // Call user service to update user
  const user = await userService.updateUser(userId, updateData);
  
  // Log user update to system logs
  await SystemLog.create({
    user_id: req.user.id, // Current user ID (from auth middleware)
    action: 'UPDATE_USER', // Action type
    entity: 'User', // Entity type
    entity_id: user.id, // Updated user ID
    payload: { updated_fields: Object.keys(updateData) }, // Log payload
  });
  
  // Log user update
  logger.info(`User updated: ${user.username}`, {
    updatedBy: req.user.id,
    userId: user.id,
  });
  
  // Return success response with updated user data
  return res.status(200).json({
    success: true, // Indicate success
    message: 'User updated successfully', // Success message
    data: { user }, // Updated user data
  });
});

/**
 * Delete user controller
 * Handles user deletion (soft delete)
 * DELETE /api/users/:id
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const deleteUser = asyncHandler(async (req, res) => {
  // Extract user ID from request parameters
  const userId = parseInt(req.params.id);
  
  // Call user service to delete user
  const user = await userService.deleteUser(userId);
  
  // Log user deletion to system logs
  await SystemLog.create({
    user_id: req.user.id, // Current user ID (from auth middleware)
    action: 'DELETE_USER', // Action type
    entity: 'User', // Entity type
    entity_id: user.id, // Deleted user ID
    payload: { username: user.username }, // Log payload
  });
  
  // Log user deletion
  logger.info(`User deleted: ${user.username}`, {
    deletedBy: req.user.id,
    userId: user.id,
  });
  
  // Return success response with deleted user data
  return res.status(200).json({
    success: true, // Indicate success
    message: 'User deleted successfully', // Success message
    data: { user }, // Deleted user data
  });
});

/**
 * List users controller
 * Handles listing users with pagination and filters
 * GET /api/users
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const listUsers = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { page, limit, role, active } = req.query;
  
  // Call user service to list users
  const result = await userService.listUsers({ page, limit, role, active });
  
  // Return success response with users list and pagination info
  return res.status(200).json({
    success: true, // Indicate success
    message: 'Users retrieved successfully', // Success message
    data: result, // Users list and pagination
  });
});

// Export controller functions
module.exports = {
  createUser, // Create user controller
  getUserById, // Get user by ID controller
  updateUser, // Update user controller
  deleteUser, // Delete user controller
  listUsers, // List users controller
};

