// backend/controllers/userController.js
import User from '../models/User.js';

export const getCurrentUser = async (req, res) => {
//  console.log('User controller: Fetching user with ID:', req.userId);
  try {
    const user = await User.findById(req.userId);
    if (!user) {
      return res.status(404).json({ message: 'User not found.' });
    }
    res.json({
      first_name: user.first_name,
      last_name: user.last_name,
      email: user.email,
    });
  } catch (error) {
    console.error('Error fetching user:', error.message);
    res.status(500).json({ message: 'Error fetching user information' });
  }
};

export const getUserById = async (req, res) => {
  const { id } = req.params;
  try {
    const user = await User.findById(id);
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    // Remove sensitive data before sending the response
    delete user.password_hash;
    res.json(user);
  } catch (error) {
    console.error('Error retrieving user by ID:', error.message);
    res.status(500).json({ message: 'Error retrieving user. Please try again later.' });
  }
};

export const getUserByEmail = async (req, res) => {
  const { email } = req.params;
  try {
    const user = await User.findByEmail(email);
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    // Remove sensitive data before sending the response
    delete user.password_hash;
    res.json(user);
  } catch (error) {
    console.error('Error retrieving user by email:', error.message);
    res.status(500).json({ message: 'Error retrieving user. Please try again later.' });
  }
};

export const getAllUsers = async (req, res) => {
  try {
    const users = await User.getAllUsers();
    if (!users.length) {
      return res.status(404).json({ message: 'No users found' });
    }
    users.forEach((user) => delete user.password_hash);
    res.json(users);
  } catch (error) {
    console.error('Error retrieving all users:', error.message);
    res.status(500).json({ message: 'Error retrieving users. Please try again later.' });
  }
};

