const { validationResult } = require('express-validator');
const userService = require('../services/userService');

/**
 * User Controller
 * Handles user profile management
 */

/**
 * Get user profile
 * @route GET /api/v1/users/profile
 */
const getProfile = async (req, res, next) => {
  try {
    const userId = req.user.id;
    const user = await userService.getUserProfile(userId);

    res.json({
      success: true,
      data: user,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Update user profile
 * @route PUT /api/v1/users/profile
 */
const updateProfile = async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'Invalid input data',
          details: errors.array(),
        },
      });
    }

    const userId = req.user.id;
    const updateData = req.body;
    
    const updatedUser = await userService.updateUserProfile(userId, updateData);

    res.json({
      success: true,
      data: updatedUser,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Set language preference
 * @route PUT /api/v1/users/language
 */
const setLanguage = async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'Invalid language code',
          details: errors.array(),
        },
      });
    }

    const userId = req.user.id;
    const { language } = req.body;
    
    const updatedUser = await userService.setUserLanguage(userId, language);

    res.json({
      success: true,
      data: updatedUser,
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  getProfile,
  updateProfile,
  setLanguage,
};
