import { Request, Response } from "express";
import { sendSuccess, sendPaginated } from "../../common/utils/api-response";
import { prisma } from "../../config/prisma";

export async function getNotifications(req: Request, res: Response) {
  const page = Math.max(1, Number(req.query.page || 1));
  const limit = Math.min(100, Math.max(1, Number(req.query.limit || 10)));

  const [data, total] = await Promise.all([
    prisma.notification.findMany({
      where: { userId: req.user!.id },
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * limit,
      take: limit,
    }),
    prisma.notification.count({ where: { userId: req.user!.id } }),
  ]);

  sendPaginated(res, data, total, page, limit);
}

export async function markAsRead(req: Request, res: Response) {
  const notification = await prisma.notification.findFirst({
    where: { id: req.params.notificationId, userId: req.user!.id },
  });

  if (!notification) {
    return res
      .status(404)
      .json({ success: false, message: "Notification not found" });
  }

  const updated = await prisma.notification.update({
    where: { id: notification.id },
    data: { status: "READ", readAt: new Date() },
  });

  sendSuccess(res, updated);
}

export async function getUnreadCount(req: Request, res: Response) {
  const count = await prisma.notification.count({
    where: { userId: req.user!.id, status: { not: "READ" } },
  });

  sendSuccess(res, { count });
}
