exports.updateDetails = async (req, res) => {
  const { username, email } = req.body;

  try {
    const user = await User.findByPk(req.user.id);

    if (user) {
      user.username = username || user.username;
      user.email = email || user.email;

      const updatedUser = await user.save();
      
      await ActivityLog.create({
        userId: user.id,
        action: 'PROFILE_UPDATE',
        ipAddress: req.ip,
        details: JSON.stringify({ username: user.username, email: user.email })
      });

      res.json({
        id: updatedUser.id,
        username: updatedUser.username,
        email: updatedUser.email,
        role: updatedUser.role,
        referralCode: updatedUser.referralCode,
        token: generateToken(updatedUser.id)
      });
    } else {
      res.status(404).json({ message: 'Usuario no encontrado' });
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al actualizar perfil' });
  }
};

exports.updatePassword = async (req, res) => {
  const { currentPassword, newPassword } = req.body;

  try {
    const user = await User.findByPk(req.user.id);

    if (user && (await bcrypt.compare(currentPassword, user.password))) {
      user.password = newPassword;
      await user.save();

      await ActivityLog.create({
        userId: user.id,
        action: 'PASSWORD_CHANGE',
        ipAddress: req.ip
      });

      res.json({ message: 'Contraseña actualizada correctamente' });
    } else {
      res.status(401).json({ message: 'Contraseña actual incorrecta' });
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al actualizar contraseña' });
  }
};
