const UserFavorite = require('../Model/UserFavorite');

exports.toggleFavorite = async (req, res) => {
  try {
    const { carData } = req.body;
    const userId = req.user._id;

    // Validate input
    if (!carData?.vin) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_VIN',
        message: 'Car data must contain a VIN number'
      });
    }

    // Check for existing favorite
    const existingFavorite = await UserFavorite.findOne({ 
      user: userId, 
      carId: carData.vin 
    });

    // If exists -> DELETE, else -> CREATE
    if (existingFavorite) {
      await UserFavorite.deleteOne({ _id: existingFavorite._id });
      return res.status(200).json({
        success: true,
        action: 'removed',
        message: 'Vehicle removed from favorites'
      });
    } else {
      const favorite = await UserFavorite.create({
        user: userId,
        carId: carData.vin,
        carData: carData
      });
      
      return res.status(201).json({
        success: true,
        action: 'added',
        data: favorite,
         message: 'Vehicle added to favorites'
      });
    }

  } catch (error) {
    console.error('Error toggling favorite:', error);

    // Handle specific errors
    if (error.name === 'ValidationError') {
      return res.status(400).json({
        success: false,
        error: 'VALIDATION_ERROR',
        message: error.message
      });
    }

    return res.status(500).json({
      success: false,
      error: 'SERVER_ERROR',
      message: 'Internal server error'
    });
  }
};

exports.getFavorites = async (req, res) => {
  try {
    const userId = req.user._id;

    // Fetch all favorite cars for the user
    const favorites = await UserFavorite.find({ user: userId });

    if (!favorites || favorites.length === 0) {
      return res.status(200).json({
        success: true,
        message: 'No favorite vehicles found for this user.',
        data: []
      });
    }

    return res.status(200).json({
      success: true,
      message: 'Favorite vehicles retrieved successfully.',
      data: favorites
    });

  } catch (error) {
    console.error('Error fetching favorite vehicles:', error);

    return res.status(500).json({
      success: false,
      error: 'SERVER_ERROR',
      message: 'Internal server error'
    });
  }
};
