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

exports.getUsers = async (req, res) => {
  try {
    const users = await User.findAll({
      include: [{ model: Wallet, as: 'wallet' }],
      attributes: { exclude: ['password'] }
    });
    res.json(users);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener usuarios' });
  }
};

exports.getUserById = async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id, {
      include: [{ model: Wallet, as: 'wallet' }],
      attributes: { exclude: ['password'] }
    });
    if (!user) {
      return res.status(404).json({ message: 'Usuario no encontrado' });
    }
    res.json(user);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener usuario' });
  }
};

exports.updateUser = async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id);
    if (!user) {
      return res.status(404).json({ message: 'Usuario no encontrado' });
    }

    const { username, email, role, password } = req.body;
    
    user.username = username || user.username;
    user.email = email || user.email;
    user.role = role || user.role;
    
    if (password) {
      user.password = password; // Hook will hash it
    }

    await user.save();
    
    res.json({ message: 'Usuario actualizado', user });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al actualizar usuario' });
  }
};

exports.deleteUser = async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id);
    if (!user) {
      return res.status(404).json({ message: 'Usuario no encontrado' });
    }
    await user.destroy();
    res.json({ message: 'Usuario eliminado' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al eliminar usuario' });
  }
};

exports.getAdminStats = async (req, res) => {
  try {
    const totalUsers = await User.count();
    const totalDeposits = await Transaction.sum('amount', { where: { type: 'deposit', status: 'completed' } }) || 0;
    const pendingDeposits = await Transaction.count({ where: { type: 'deposit', status: 'pending' } });
    const totalWithdrawals = await Transaction.sum('amount', { where: { type: 'withdrawal', status: 'completed' } }) || 0;
    const pendingWithdrawals = await Transaction.count({ where: { type: 'withdrawal', status: 'pending' } });

    res.json({
      totalUsers,
      totalDeposits,
      pendingDeposits,
      totalWithdrawals,
      pendingWithdrawals
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener estadísticas' });
  }
};
