const { Router } = require("express");
const prisma = require("../prisma");
const { requireAuth } = require("../middleware/auth");

const router = Router();

router.get("/", requireAuth, async (req, res, next) => {
  try {
    const userId = req.user.sub;
    const page = Math.max(1, parseInt(req.query.page) || 1);
    const limit = Math.min(50, Math.max(1, parseInt(req.query.limit) || 20));
    const skip = (page - 1) * limit;
    const unreadOnly = req.query.unread === "true";

    const where = { userId };
    if (unreadOnly) where.isRead = false;

    const [total, rows, unreadCount] = await Promise.all([
      prisma.notification.count({ where }),
      prisma.notification.findMany({
        where,
        orderBy: { createdAt: "desc" },
        skip,
        take: limit,
      }),
      prisma.notification.count({ where: { userId, isRead: false } }),
    ]);

    return res.json({
      data: rows,
      unreadCount,
      pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
    });
  } catch (err) {
    return next(err);
  }
});

router.patch("/:id/read", requireAuth, async (req, res, next) => {
  try {
    const row = await prisma.notification.findFirst({
      where: { id: req.params.id, userId: req.user.sub },
    });
    if (!row) return res.status(404).json({ error: "Not found" });
    const updated = await prisma.notification.update({
      where: { id: row.id },
      data: { isRead: true },
    });
    return res.json(updated);
  } catch (err) {
    return next(err);
  }
});

router.post("/read-all", requireAuth, async (req, res, next) => {
  try {
    await prisma.notification.updateMany({
      where: { userId: req.user.sub, isRead: false },
      data: { isRead: true },
    });
    return res.json({ ok: true });
  } catch (err) {
    return next(err);
  }
});

module.exports = router;
