import { Router } from "express";

import { prisma } from "../db";
import { requireAuth, type AuthRequest } from "../middleware/auth";

export const notificationRouter = Router();
notificationRouter.use(requireAuth);

notificationRouter.get("/", async (req: AuthRequest, res) => {
  const status = (req.query.status as string | undefined) ?? "all";
  const where =
    status === "unread"
      ? { recipientId: req.userId!, readAt: null }
      : { recipientId: req.userId! };

  const notifications = await prisma.notification.findMany({
    where,
    orderBy: { triggerAt: "desc" },
  });
  return res.json(notifications);
});

notificationRouter.post("/:id/read", async (req: AuthRequest, res) => {
  const updated = await prisma.notification.updateMany({
    where: { id: req.params.id, recipientId: req.userId! },
    data: { readAt: new Date() },
  });
  if (updated.count === 0) {
    return res.status(404).json({ error: "Not found" });
  }
  return res.json({ ok: true });
});

notificationRouter.post("/read-all", async (req: AuthRequest, res) => {
  await prisma.notification.updateMany({
    where: { recipientId: req.userId!, readAt: null },
    data: { readAt: new Date() },
  });
  return res.json({ ok: true });
});
