import { Router } from "express";
import { Notification } from "@/db/models";
import { asyncHandler } from "@/lib/errors";
import { requireAuth } from "@/middleware/auth";
import { toPlain } from "@/lib/serialize";
import { isNotificationsMysql } from "@/db/activeDatabase";
import {
  listNotificationsMysql,
  markAllNotificationsReadMysql,
  markNotificationReadMysql,
  notificationToApi,
} from "@/db/mysql/notifications";

export const notificationsRouter = Router();

notificationsRouter.get(
  "/",
  requireAuth,
  asyncHandler(async (req, res) => {
    if (isNotificationsMysql()) {
      const { notifications, unreadCount } = await listNotificationsMysql(req.user!.id, 50);
      res.json({
        notifications: notifications.map(notificationToApi),
        unreadCount,
        _db: "mysql",
      });
      return;
    }

    const notifications = await Notification.find({ userId: req.user!.id })
      .sort({ createdAt: -1 })
      .limit(50)
      .lean();
    const unreadCount = await Notification.countDocuments({
      userId: req.user!.id,
      readAt: null,
    });
    res.json({ notifications: notifications.map(toPlain), unreadCount, _db: "mongodb" });
  }),
);

notificationsRouter.post(
  "/:id/read",
  requireAuth,
  asyncHandler(async (req, res) => {
    if (isNotificationsMysql()) {
      await markNotificationReadMysql(req.params.id, req.user!.id);
      res.json({ ok: true, _db: "mysql" });
      return;
    }
    await Notification.updateOne(
      { _id: req.params.id, userId: req.user!.id },
      { $set: { readAt: new Date() } },
    );
    res.json({ ok: true, _db: "mongodb" });
  }),
);

notificationsRouter.post(
  "/read-all",
  requireAuth,
  asyncHandler(async (req, res) => {
    if (isNotificationsMysql()) {
      await markAllNotificationsReadMysql(req.user!.id);
      res.json({ ok: true, _db: "mysql" });
      return;
    }
    await Notification.updateMany(
      { userId: req.user!.id, readAt: null },
      { $set: { readAt: new Date() } },
    );
    res.json({ ok: true, _db: "mongodb" });
  }),
);
