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

/**
 * Admin User Controller
 * Handles HTTP requests for user management in admin panel
 */

/**
 * Get user list with pagination and filters
 * @route GET /api/v1/admin/users
 */
const getUserList = async (req, res) => {
  try {
    const {
      page,
      limit,
      search,
      status,
      language,
      sortBy,
      sortOrder,
    } = req.query;

    const result = await adminUserService.getUserList({
      page,
      limit,
      search,
      status,
      language,
      sortBy,
      sortOrder,
    });

    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: {
        code: 'GET_USER_LIST_ERROR',
        message: 'Failed to retrieve user list',
        details: error.message,
      },
    });
  }
};

/**
 * Get user details
 * @route GET /api/v1/admin/users/:id
 */
const getUserDetails = async (req, res) => {
  try {
    const { id } = req.params;

    const result = await adminUserService.getUserDetails(id);

    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    if (error.message === 'User not found') {
      return res.status(404).json({
        success: false,
        error: {
          code: 'USER_NOT_FOUND',
          message: 'User not found',
        },
      });
    }

    res.status(500).json({
      success: false,
      error: {
        code: 'GET_USER_DETAILS_ERROR',
        message: 'Failed to retrieve user details',
        details: error.message,
      },
    });
  }
};

/**
 * Update user status
 * @route PUT /api/v1/admin/users/:id/status
 */
const updateUserStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    if (!status) {
      return res.status(400).json({
        success: false,
        error: {
          code: 'MISSING_STATUS',
          message: 'Status is required',
        },
      });
    }

    const user = await adminUserService.updateUserStatus(id, status);

    res.json({
      success: true,
      data: {
        user: {
          id: user.id,
          status: user.status,
          updatedAt: user.updatedAt,
        },
      },
      message: 'User status updated successfully',
    });
  } catch (error) {
    if (error.message === 'User not found') {
      return res.status(404).json({
        success: false,
        error: {
          code: 'USER_NOT_FOUND',
          message: 'User not found',
        },
      });
    }

    if (error.message === 'Invalid status value') {
      return res.status(400).json({
        success: false,
        error: {
          code: 'INVALID_STATUS',
          message: 'Invalid status value. Must be "active" or "suspended"',
        },
      });
    }

    res.status(500).json({
      success: false,
      error: {
        code: 'UPDATE_STATUS_ERROR',
        message: 'Failed to update user status',
        details: error.message,
      },
    });
  }
};

/**
 * Export users to CSV
 * @route GET /api/v1/admin/users/export/csv
 */
const exportUsersToCSV = async (req, res) => {
  try {
    const { search, status, language } = req.query;

    const csv = await adminUserService.exportUsersToCSV({
      search,
      status,
      language,
    });

    // Set headers for CSV download
    res.setHeader('Content-Type', 'text/csv');
    res.setHeader('Content-Disposition', `attachment; filename=users-${Date.now()}.csv`);
    
    res.send(csv);
  } catch (error) {
    res.status(500).json({
      success: false,
      error: {
        code: 'EXPORT_CSV_ERROR',
        message: 'Failed to export users to CSV',
        details: error.message,
      },
    });
  }
};

module.exports = {
  getUserList,
  getUserDetails,
  updateUserStatus,
  exportUsersToCSV,
};
