const { User } = require('../models');

// @desc    Get all users
// @route   GET /api/users
// @access  Public
exports.getUsers = async (req, res) => {
  try {
    const users = await User.findAll({
      attributes: { exclude: ['password'] }
    });
    
    res.status(200).json(users);
  } catch (error) {
    console.error('Error in getUsers:', error);
    res.status(500).json({
      message: 'Error retrieving users',
      error: error.message
    });
  }
};

// @desc    Get single user
// @route   GET /api/users/:id
// @access  Public
exports.getUser = async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id, {
      attributes: { exclude: ['password'] }
    });
    
    if (!user) {
      return res.status(404).json({
        message: 'User not found'
      });
    }
    
    res.status(200).json(user);
  } catch (error) {
    console.error('Error in getUser:', error);
    res.status(500).json({
      message: 'Error retrieving user',
      error: error.message
    });
  }
};

// @desc    Create user
// @route   POST /api/users
// @access  Public
exports.createUser = async (req, res) => {
  try {
    // Check if user with email already exists
    const existingUser = await User.findOne({ where: { email: req.body.email } });
    
    if (existingUser) {
      return res.status(409).json({
        message: 'Ya existe un usuario con ese email'
      });
    }
    
    // Set default password if not provided
    if (!req.body.password) {
      req.body.password = 'password123';
    }
    
    const user = await User.create(req.body);
    
    // Remove password from response
    const userResponse = user.toJSON();
    delete userResponse.password;
    
    res.status(201).json(userResponse);
  } catch (error) {
    console.error('Error in createUser:', error);
    res.status(500).json({
      message: 'Error creating user',
      error: error.message
    });
  }
};

// @desc    Update user
// @route   PUT /api/users/:id
// @access  Public
exports.updateUser = async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id);
    
    if (!user) {
      return res.status(404).json({
        message: 'User not found'
      });
    }
    
    // Don't allow email to be updated
    delete req.body.email;
    
    await user.update(req.body);
    
    // Remove password from response
    const userResponse = user.toJSON();
    delete userResponse.password;
    
    res.status(200).json(userResponse);
  } catch (error) {
    console.error('Error in updateUser:', error);
    res.status(500).json({
      message: 'Error updating user',
      error: error.message
    });
  }
};