const mongoose = require('mongoose');
const { listNotifications, unreadCount } = require('@/services/notifications/service');

const scope = (req) => ({ tenant: req.tenantId, admin: req.admin?._id, removed: false });

const list = async (req, res) => {
  const result = await listNotifications({
    tenantId: req.tenantId,
    recipientId: req.admin?._id,
    unreadOnly: req.query.unread === 'true',
    limit: Number(req.query.limit || 50),
  });
  return res.status(200).json({ success: true, result, message: 'Notifications loaded' });
};

const read = async (req, res) => {
  const result = await mongoose.model('Notification').findOneAndUpdate(
    { _id: req.params.id, tenant: req.tenantId, recipient: req.admin?._id, removed: false },
    { readAt: new Date() },
    { new: true }
  );
  return res.status(200).json({ success: true, result, message: 'Notification marked as read' });
};

const readAll = async (req, res) => {
  const result = await mongoose.model('Notification').updateMany(
    { tenant: req.tenantId, recipient: req.admin?._id, removed: false, readAt: { $exists: false } },
    { readAt: new Date() }
  );
  return res.status(200).json({ success: true, result, message: 'Notifications marked as read' });
};

const preferences = async (req, res) => {
  let result = await mongoose.model('NotificationPreference').findOne(scope(req)).lean();
  if (!result) {
    result = await mongoose.model('NotificationPreference').create({
      tenant: req.tenantId,
      createdBy: req.admin?._id,
      assignedTo: req.admin?._id,
      admin: req.admin?._id,
      inApp: true,
      email: true,
      whatsapp: false,
      eventPreferences: {},
    });
  }
  return res.status(200).json({ success: true, result, message: 'Notification preferences loaded' });
};

const updatePreferences = async (req, res) => {
  const result = await mongoose.model('NotificationPreference').findOneAndUpdate(
    scope(req),
    {
      $set: {
        inApp: req.body?.inApp !== false,
        email: req.body?.email !== false,
        whatsapp: req.body?.whatsapp === true,
        eventPreferences: req.body?.eventPreferences || {},
      },
      $setOnInsert: {
        tenant: req.tenantId,
        createdBy: req.admin?._id,
        assignedTo: req.admin?._id,
        admin: req.admin?._id,
      },
    },
    { upsert: true, new: true, setDefaultsOnInsert: true }
  );
  return res.status(200).json({ success: true, result, message: 'Notification preferences updated' });
};

const unread = async (req, res) =>
  res.status(200).json({
    success: true,
    result: { count: await unreadCount({ tenantId: req.tenantId, recipientId: req.admin?._id }) },
    message: 'Unread notification count loaded',
  });

module.exports = { list, read, readAll, preferences, updatePreferences, unread };
