import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { connectDB } from "@/lib/db";
import { Notification } from "@/models/Notification";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

export async function OPTIONS(request: NextRequest) {
  return corsPreflight(request);
}

export async function GET(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  await connectDB();
  const raw = await Notification.find({ recipientId: clientId }).sort({ createdAt: -1 }).limit(100).lean();
  const notifications = raw.map((n) => ({
    _id: String(n._id),
    title: n.title,
    body: n.body || "",
    link: n.link || null,
    read: n.read,
    createdAt: new Date(n.createdAt).toISOString(),
  }));
  return NextResponse.json({ notifications }, { headers });
}
