const { Review, Customer, Booking } = require('../models');

class ReviewController {
  async getAll(req, res, next) {
    try {
      const reviews = await Review.findAll({
        include: [{ model: Customer }, { model: Booking }],
        order: [['created_at', 'DESC']],
      });
      res.json({ reviews });
    } catch (error) {
      next(error);
    }
  }

  async getFeatured(req, res, next) {
    try {
      const reviews = await Review.findAll({
        where: { is_featured: true, is_verified: true },
        include: [{ model: Customer }],
        order: [['created_at', 'DESC']],
        limit: 10,
      });
      res.json({ reviews });
    } catch (error) {
      next(error);
    }
  }

  async getById(req, res, next) {
    try {
      const review = await Review.findByPk(req.params.id, {
        include: [{ model: Customer }, { model: Booking }],
      });
      if (!review) {
        return res.status(404).json({ error: 'Review not found' });
      }
      res.json({ review });
    } catch (error) {
      next(error);
    }
  }

  async create(req, res, next) {
    try {
      const { booking_id, customer_id } = req.body;

      const existing = await Review.findOne({ where: { booking_id, customer_id } });
      if (existing) {
        return res.status(409).json({ error: 'Review already exists for this booking' });
      }

      const review = await Review.create(req.body);
      res.status(201).json({ review });
    } catch (error) {
      next(error);
    }
  }

  async update(req, res, next) {
    try {
      const review = await Review.findByPk(req.params.id);
      if (!review) {
        return res.status(404).json({ error: 'Review not found' });
      }
      await review.update(req.body);
      res.json({ review });
    } catch (error) {
      next(error);
    }
  }

  async remove(req, res, next) {
    try {
      const review = await Review.findByPk(req.params.id);
      if (!review) {
        return res.status(404).json({ error: 'Review not found' });
      }
      await review.destroy();
      res.json({ message: 'Review deleted' });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new ReviewController();
