import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";

/** All support tickets of registered institutions (optional ?status= filter),
    with reply/attachment counts + last activity for the support panel. */
export async function GET(req: Request) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const statusParam = new URL(req.url).searchParams.get("status");
  const status = ["OPEN", "IN_PROGRESS", "RESOLVED", "CLOSED"].includes(statusParam ?? "")
    ? (statusParam as "OPEN" | "IN_PROGRESS" | "RESOLVED" | "CLOSED")
    : undefined;

  const tickets = await prisma.supportTicket.findMany({
    where: status ? { status } : undefined,
    orderBy: [{ updatedAt: "desc" }, { id: "desc" }],
    include: {
      institution: { select: { id: true, name: true, type: true } },
      _count: { select: { messages: true, attachments: true } },
      messages: { orderBy: { createdAt: "desc" }, take: 1, select: { senderRole: true, createdAt: true } },
    },
  });

  return NextResponse.json({
    tickets: tickets.map(({ messages, _count, ...t }) => ({
      ...t,
      replyCount: _count.messages,
      attachmentCount: _count.attachments,
      lastReplyBy: messages[0]?.senderRole ?? null,
      lastActivityAt: messages[0]?.createdAt ?? t.createdAt,
    })),
  });
}
