const Booking = require('../models/Booking');
const Restaurant = require('../models/Restaurant');

exports.createBooking = async (req, res) => {
  try {
    const { restaurantId, guests, bookingDate, bookingTime } = req.body;

    const booking = new Booking({
      user: req.user._id,
      restaurant: restaurantId,
      guests,
      bookingDate,
      bookingTime,
    });

    const savedBooking = await booking.save();
    res.status(201).json(savedBooking);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.getUserBookings = async (req, res) => {
  try {
    const bookings = await Booking.find({ user: req.user._id }).populate('restaurant');
    res.json(bookings);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.getOwnerBookings = async (req, res) => {
  try {
    const restaurants = await Restaurant.find({ owner: req.user._id });
    const restaurantIds = restaurants.map(r => r._id);
    const bookings = await Booking.find({ restaurant: { $in: restaurantIds } })
      .populate('user', 'name email')
      .populate('restaurant', 'name');
    res.json(bookings);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.cancelBooking = async (req, res) => {
  try {
    const booking = await Booking.findById(req.params.id);
    if (!booking) return res.status(404).json({ message: 'Booking not found' });
    
    // Ensure only the user who made the booking or the owner can cancel
    if (booking.user.toString() !== req.user._id.toString()) {
        return res.status(401).json({ message: 'Not authorized' });
    }

    await booking.deleteOne();
    res.json({ message: 'Booking removed' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
