import { Router } from 'express';
import { prisma } from '../config/database.js';
import { authenticate } from '../middleware/auth.js';
import { AppError } from '../middleware/errorHandler.js';

const router = Router();

// --- Unread count (must be before /:id) ---
router.get('/unread-count', authenticate, async (req, res, next) => {
  try {
    const count = await prisma.notification.count({
      where: { userId: req.userId, isRead: false },
    });
    res.json({ count });
  } catch (error) {
    next(error);
  }
});

// --- List notifications with pagination ---
router.get('/', authenticate, async (req, res, next) => {
  try {
    const { page = '1', pageSize = '20' } = req.query;
    const take = parseInt(pageSize as string);
    const skip = (parseInt(page as string) - 1) * take;

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

    res.json({
      data: notifications,
      total,
      page: parseInt(page as string),
      pageSize: take,
      totalPages: Math.ceil(total / take),
    });
  } catch (error) {
    next(error);
  }
});

// --- Mark all as read ---
router.patch('/read-all', authenticate, async (req, res, next) => {
  try {
    await prisma.notification.updateMany({
      where: { userId: req.userId, isRead: false },
      data: { isRead: true },
    });
    res.json({ message: 'All notifications marked as read' });
  } catch (error) {
    next(error);
  }
});

// --- Mark single as read ---
router.patch('/:id/read', authenticate, async (req, res, next) => {
  try {
    const notification = await prisma.notification.findUnique({ where: { id: req.params.id } });
    if (!notification) throw new AppError(404, 'Notification not found');
    if (notification.userId !== req.userId) throw new AppError(403, 'Not authorized');

    await prisma.notification.update({
      where: { id: req.params.id },
      data: { isRead: true },
    });
    res.json({ message: 'Notification marked as read' });
  } catch (error) {
    next(error);
  }
});

// --- Delete notification ---
router.delete('/:id', authenticate, async (req, res, next) => {
  try {
    const notification = await prisma.notification.findUnique({ where: { id: req.params.id } });
    if (!notification) throw new AppError(404, 'Notification not found');
    if (notification.userId !== req.userId) throw new AppError(403, 'Not authorized');

    await prisma.notification.delete({ where: { id: req.params.id } });
    res.json({ message: 'Notification deleted' });
  } catch (error) {
    next(error);
  }
});

export default router;
