import { Router } from 'express';
import { prisma } from '../db';
import { AuthedRequest, requireAuth } from '../middleware/auth';

export const notificationsRouter = Router();
notificationsRouter.use(requireAuth);

notificationsRouter.get('/', async (req: AuthedRequest, res, next) => {
  try {
    const rows = await prisma.notification.findMany({
      where: { employeeId: req.user!.id },
      orderBy: { at: 'desc' },
      take: 100,
    });
    res.json({
      notifications: rows.map((n) => ({
        id: n.id,
        text: n.text,
        read: n.read,
        at: n.at.toISOString(),
      })),
      unread: rows.filter((n) => !n.read).length,
    });
  } catch (err) {
    next(err);
  }
});

notificationsRouter.post('/read-all', async (req: AuthedRequest, res, next) => {
  try {
    await prisma.notification.updateMany({
      where: { employeeId: req.user!.id, read: false },
      data: { read: true },
    });
    res.json({ ok: true });
  } catch (err) {
    next(err);
  }
});
