import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { pushNotification } from "@/lib/notify-push";

/** Central platform announcements — pushed to the chosen role groups across
    every institution (institutionId null) and shown in each credential's
    notification bell. */

export async function GET() {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const rows = await prisma.appNotification.findMany({
    where: { institutionId: null },
    orderBy: { createdAt: "desc" },
    take: 100,
    include: { reads: { select: { id: true } } },
  });

  return NextResponse.json({
    announcements: rows.map((n) => ({
      id: n.id,
      title: n.title,
      body: n.body,
      createdAt: n.createdAt,
      audienceRoles: n.audienceRoles,
      reached: n.reads.length,
    })),
  });
}

export async function POST(req: Request) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const title = String(body.title ?? "").trim();
    const text = String(body.body ?? "").trim() || null;
    const groups: string[] = Array.isArray(body.notifyGroups)
      ? body.notifyGroups.map(String).filter((g: string) => ["students", "parents", "teachers", "staff", "admins"].includes(g))
      : [];
    if (!title) return NextResponse.json({ error: "TITLE_REQUIRED" }, { status: 400 });
    if (groups.length === 0) return NextResponse.json({ error: "AUDIENCE_REQUIRED" }, { status: 400 });

    const id = await pushNotification({
      institutionId: null,
      kind: "SYSTEM",
      title,
      body: text,
      link: null,
      audience: groups,
      createdById: session.userId,
    });
    return NextResponse.json({ success: true, id });
  } catch {
    return NextResponse.json({ error: "Could not publish announcement" }, { status: 500 });
  }
}

export async function DELETE(req: Request) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const id = Number(new URL(req.url).searchParams.get("id") ?? "");
  if (!Number.isInteger(id) || id <= 0) {
    return NextResponse.json({ error: "BAD_ID" }, { status: 400 });
  }
  await prisma.appNotification.deleteMany({ where: { id, institutionId: null } });
  return NextResponse.json({ success: true });
}
