import { Router } from 'express';
import prisma from '../lib/prisma';
import { asyncHandler, sendSuccess, getPagination, buildPaginationMeta, paramId } from '../lib/utils';
import { authenticate, AuthRequest } from '../middleware/auth';

const router = Router();

const excludeMessageNotifications = { type: { not: 'MESSAGE_RECEIVED' as const } };

router.get(
  '/',
  authenticate,
  asyncHandler(async (req: AuthRequest, res) => {
    const { page, limit, skip } = getPagination(req.query);
    const unreadOnly = req.query.unread === 'true';

    const where = {
      userId: req.user!.userId,
      ...excludeMessageNotifications,
      ...(unreadOnly ? { isRead: false } : {}),
    };

    const [notifications, total] = await Promise.all([
      prisma.notification.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
      }),
      prisma.notification.count({ where }),
    ]);

    sendSuccess(res, notifications, undefined, 200, buildPaginationMeta(total, page, limit));
  })
);

router.get(
  '/unread-count',
  authenticate,
  asyncHandler(async (req: AuthRequest, res) => {
    const count = await prisma.notification.count({
      where: { userId: req.user!.userId, isRead: false, ...excludeMessageNotifications },
    });
    sendSuccess(res, { count });
  })
);

router.patch(
  '/:id/read',
  authenticate,
  asyncHandler(async (req: AuthRequest, res) => {
    const notification = await prisma.notification.updateMany({
      where: { id: paramId(req.params.id), userId: req.user!.userId },
      data: { isRead: true, readAt: new Date() },
    });
    sendSuccess(res, { updated: notification.count });
  })
);

router.patch(
  '/read-all',
  authenticate,
  asyncHandler(async (req: AuthRequest, res) => {
    const result = await prisma.notification.updateMany({
      where: { userId: req.user!.userId, isRead: false, ...excludeMessageNotifications },
      data: { isRead: true, readAt: new Date() },
    });
    sendSuccess(res, { updated: result.count }, 'All notifications marked as read');
  })
);

export default router;
