import { NextResponse } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { connectDB } from "@/lib/db";
import { Notification } from "@/models/Notification";

// Von der Glocke (Admin wie Kunde) periodisch abgerufen — bewusst ein
// gemeinsamer Endpunkt für beide, da nur die Session entscheidet, wessen
// Benachrichtigungen zurückkommen.
export async function GET() {
  const clientId = await getSessionClientId();
  if (!clientId) return NextResponse.json({ unreadCount: 0, notifications: [] });

  await connectDB();
  const [unreadCount, notifications] = await Promise.all([
    Notification.countDocuments({ recipientId: clientId, read: false }),
    Notification.find({ recipientId: clientId }).sort({ createdAt: -1 }).limit(8).lean(),
  ]);

  return NextResponse.json({
    unreadCount,
    notifications: notifications.map((n) => ({
      id: String(n._id),
      title: n.title,
      body: n.body,
      link: n.link,
      read: n.read,
      createdAt: n.createdAt,
    })),
  });
}
