const { UserNotification, User } = require('../models');
const { Op } = require('sequelize');

class UserNotificationController {
  async getAll(req, res, next) {
    try {
      const notifications = await UserNotification.findAll({
        where: { user_email: req.user.email },
        order: [['created_at', 'DESC']],
        limit: 50,
      });
      const unreadCount = await UserNotification.count({
        where: { user_email: req.user.email, is_read: false },
      });
      res.json({ notifications, unread_count: unreadCount });
    } catch (error) {
      next(error);
    }
  }

  async markRead(req, res, next) {
    try {
      const { id } = req.params;
      if (id === 'all') {
        await UserNotification.update(
          { is_read: true },
          { where: { user_email: req.user.email, is_read: false } }
        );
      } else {
        await UserNotification.update(
          { is_read: true },
          { where: { id, user_email: req.user.email } }
        );
      }
      res.json({ message: 'Marked as read' });
    } catch (error) {
      next(error);
    }
  }

  async unreadCount(req, res, next) {
    try {
      const count = await UserNotification.count({
        where: { user_email: req.user.email, is_read: false },
      });
      res.json({ unread_count: count });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new UserNotificationController();
