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

exports.createRestaurant = async (req, res) => {
  try {
    const { name, location, description, openingTime, closingTime, tables, cuisine } = req.body;

    const restaurant = new Restaurant({
      owner: req.user._id,
      name,
      location,
      description,
      openingTime,
      closingTime,
      tables: tables || [],
      cuisine,
    });

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

exports.getAllRestaurants = async (req, res) => {
  try {
    const restaurants = await Restaurant.find().populate('owner', 'name email');
    res.json(restaurants);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.getRestaurantById = async (req, res) => {
  try {
    const restaurant = await Restaurant.findById(req.params.id);
    if (!restaurant) {
      return res.status(404).json({ message: 'Restaurant not found' });
    }
    res.json(restaurant);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.updateRestaurant = async (req, res) => {
  try {
    const { 
      name, 
      location, 
      description, 
      openingTime, 
      closingTime, 
      cuisine, 
      priceRange,
      menu 
    } = req.body;

    const restaurant = await Restaurant.findOne({ owner: req.user._id });
    
    if (!restaurant) {
      return res.status(404).json({ message: 'Restaurant not found' });
    }

    if (name) restaurant.name = name;
    if (location) restaurant.location = location;
    if (description) restaurant.description = description;
    if (openingTime) restaurant.openingTime = openingTime;
    if (closingTime) restaurant.closingTime = closingTime;
    if (cuisine) restaurant.cuisine = cuisine;
    if (priceRange) restaurant.priceRange = priceRange;
    if (menu) restaurant.menu = typeof menu === 'string' ? JSON.parse(menu) : menu;

    if (req.file) {
      restaurant.image = req.file.path.replace(/\\/g, '/');
    }

    await restaurant.save();
    res.json(restaurant);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.updateRestaurantTables = async (req, res) => {
  try {
    const { tables } = req.body;
    const restaurant = await Restaurant.findOne({ owner: req.user._id });
    
    if (!restaurant) {
      return res.status(404).json({ message: 'Restaurant not found' });
    }

    restaurant.tables = tables;
    await restaurant.save();
    
    res.json(restaurant);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
