const User = require('../models/user');

// Get single user by ID
exports.getUser = async (req, res) => {
    try {
        const user = await User.findById(req.params.id)
                              .select('-password');
        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }
        res.status(200).json(user);
    } catch (error) {
        res.status(500).json({ 
            message: 'Server error retrieving user',
            error: error.message 
        });
    }
};

// Create new user
exports.register = async (req, res) => {
    try {
        const { email } = req.body;
        
        // Check for existing user
        const existingUser = await User.findOne({ email });
        if (existingUser) {
            return res.status(400).json({ message: 'User already exists' });
        }

        const newUser = new User(req.body);
        await newUser.save();
        
        // Return user without password
        const userResponse = newUser.toObject();
        delete userResponse.password;
        
        res.status(201).json(userResponse);
    } catch (error) {
        res.status(400).json({
            message: 'Validation failed',
            errors: error.errors ? Object.values(error.errors).map(e => e.message) : [error.message]
        });
    }
};

// Update user
exports.updateUser = async (req, res) => {
    try {
        const user = await User.findByIdAndUpdate(
            req.params.id,
            req.body,
            { new: true, runValidators: true }
        ).select('-password');

        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }
        
        res.status(200).json(user);
    } catch (error) {
        res.status(400).json({
            message: 'Update failed',
            errors: error.errors ? Object.values(error.errors).map(e => e.message) : [error.message]
        });
    }
};

// Get all users (with pagination)
exports.getAll = async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const skip = (page - 1) * limit;

        const users = await User.find()
                               .select('-password')
                               .skip(skip)
                               .limit(limit);

        res.status(200).json({
            count: users.length,
            page,
            totalPages: Math.ceil(await User.countDocuments() / limit),
            users
        });
    } catch (error) {
        res.status(500).json({
            message: 'Server error retrieving users',
            error: error.message
        });
    }
};

exports.getProfile = async (req, res) => {
    try {
    console.log(req.user.userId);
      const user = await User.findById(req.user.userId)
        .select('username profile_pic number_of_cars number_of_friends garage posts');
      
      if (!user) {
        return res.status(404).json({ message: 'User not found' });
      }
      res.status(200).json(user);
    } catch (error) {
    console.error('Error retrieving user:', error);
      res.status(500).json({ 
        message: 'Server error retrieving user',
        error: error.message 
      });
    }
  };