import { notFound } from "next/navigation";
import { prisma } from "@/lib/db";
import TicketWorkspace from "./TicketWorkspace";

export const dynamic = "force-dynamic";

export default async function AdminTicketDetail({ params }) {
  const ticket = await prisma.ticket.findUnique({
    where: { id: Number(params.id) || 0 },
    include: {
      project: { include: { categories: true } },
      category: true,
      user: { select: { id: true, name: true, email: true, createdAt: true } },
      assignee: { select: { id: true, name: true } },
      messages: { orderBy: { id: "asc" } },
    },
  });
  if (!ticket) notFound();

  const [agents, canned, customerTicketCount] = await Promise.all([
    prisma.user.findMany({
      where: {
        role: { in: ["AGENT", "ADMIN"] },
        active: true,
        OR: [{ role: "ADMIN" }, { projects: { some: { projectId: ticket.projectId } } }],
      },
      select: { id: true, name: true, role: true },
    }),
    prisma.cannedResponse.findMany({ orderBy: { id: "asc" } }),
    ticket.userId
      ? prisma.ticket.count({ where: { userId: ticket.userId } })
      : prisma.ticket.count({ where: { guestEmail: ticket.guestEmail || "∅" } }),
  ]);

  return (
    <TicketWorkspace
      ticket={JSON.parse(JSON.stringify(ticket))}
      agents={agents}
      canned={canned}
      customerTicketCount={customerTicketCount}
    />
  );
}
