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

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

  async getByBooking(req, res, next) {
    try {
      const notifications = await Notification.findAll({
        where: { booking_id: req.params.bookingId },
        order: [['created_at', 'DESC']],
      });
      res.json({ notifications });
    } catch (error) {
      next(error);
    }
  }

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

  async create(req, res, next) {
    try {
      const notification = await Notification.create(req.body);
      res.status(201).json({ notification });
    } catch (error) {
      next(error);
    }
  }

  async updateStatus(req, res, next) {
    try {
      const { status, error_message } = req.body;
      const notification = await Notification.findByPk(req.params.id);
      if (!notification) {
        return res.status(404).json({ error: 'Notification not found' });
      }
      notification.status = status || notification.status;
      if (status === 'sent') notification.sent_at = new Date();
      if (error_message) notification.error_message = error_message;
      await notification.save();
      res.json({ notification });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new NotificationController();
