/**
 * GET /api/notifications/count?brandId=X — unread count for bell badge.
 *
 * Unions two sources:
 *   1. Notification table where isRead=false and channel="in_app".
 *   2. Signal + rank-change SiteEvent rows where the detection engine
 *      or rank-check cron has emitted an unread alert (see
 *      listSignalEvents / countUnreadSignalEvents for the exact types).
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { countUnreadSignalEvents } from "@/lib/services/notification-sources";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const brandId = new URL(req.url).searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const [notifCount, signalCount] = await Promise.all([
    prisma.notification.count({ where: { brandId, isRead: false, channel: "in_app" } }),
    countUnreadSignalEvents(brandId),
  ]);
  return NextResponse.json({
    count: notifCount + signalCount,
    breakdown: { notifications: notifCount, signals: signalCount },
  });
}
