import type { Request, Response } from "express";
import { prisma } from "../../config/prisma.js";
import { asyncHandler } from "../../utils/asyncHandler.js";

export const listNotifications = asyncHandler(async (req: Request, res: Response) => {
  const { type, read, limit } = req.query;
  const where: any = {};
  if (type) where.type = String(type);
  if (read === "true") where.readAt = { not: null };
  if (read === "false") where.readAt = null;

  const notifications = await prisma.notification.findMany({
    where,
    include: { document: { include: { documentType: true, employee: true, company: true } } },
    orderBy: { createdAt: "desc" },
    take: Number(limit || 100),
  });
  const unread = await prisma.notification.count({ where: { readAt: null } });
  res.json({ success: true, data: { notifications, unread } });
});

export const markRead = asyncHandler(async (req: Request, res: Response) => {
  await prisma.notification.updateMany({
    where: { id: { in: req.body.ids as number[] }, readAt: null },
    data: { readAt: new Date() },
  });
  const unread = await prisma.notification.count({ where: { readAt: null } });
  res.json({ success: true, data: { unread } });
});

export const markAllRead = asyncHandler(async (_req: Request, res: Response) => {
  await prisma.notification.updateMany({ where: { readAt: null }, data: { readAt: new Date() } });
  res.json({ success: true });
});
