import { Response } from 'express';
import { prisma } from '../config/database';
import { AuthRequest } from '../middleware/auth';

export async function listNotifications(req: AuthRequest, res: Response): Promise<void> {
  try {
    const limit = Math.max(1, Math.min(100, Number(req.query.limit) || 20));
    const onlyUnread = req.query.unread === 'true';

    const where: any = { organizerId: req.organizerId };
    if (onlyUnread) where.read = false;

    const [items, unreadCount] = await Promise.all([
      prisma.notification.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        take: limit,
        include: {
          attendee: { select: { id: true, name: true, shortId: true } },
          event: { select: { id: true, name: true } },
        },
      }),
      prisma.notification.count({
        where: { organizerId: req.organizerId, read: false },
      }),
    ]);

    res.json({ items, unreadCount });
  } catch (error) {
    console.error('listNotifications error:', error);
    res.status(500).json({ error: 'Failed to fetch notifications' });
  }
}

export async function markRead(req: AuthRequest, res: Response): Promise<void> {
  try {
    const { id } = req.params;
    const existing = await prisma.notification.findFirst({
      where: { id, organizerId: req.organizerId },
    });
    if (!existing) {
      res.status(404).json({ error: 'Notification not found' });
      return;
    }
    const updated = await prisma.notification.update({
      where: { id },
      data: { read: true, readAt: existing.readAt || new Date() },
    });
    res.json(updated);
  } catch (error) {
    console.error('markRead error:', error);
    res.status(500).json({ error: 'Failed to mark notification as read' });
  }
}

export async function markAllRead(req: AuthRequest, res: Response): Promise<void> {
  try {
    const result = await prisma.notification.updateMany({
      where: { organizerId: req.organizerId, read: false },
      data: { read: true, readAt: new Date() },
    });
    res.json({ updated: result.count });
  } catch (error) {
    console.error('markAllRead error:', error);
    res.status(500).json({ error: 'Failed to mark all as read' });
  }
}
