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

type Params = { params: Promise<{ id: string }> };

/** One of the institution's own tickets: full conversation + attachment meta. */
export async function GET(_req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const ticket = await prisma.supportTicket.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    include: {
      messages: { orderBy: { createdAt: "asc" } },
      attachments: { select: { id: true, fileName: true, mimeType: true, fileSize: true, createdAt: true } },
    },
  });
  if (!ticket) return NextResponse.json({ error: "Not found" }, { status: 404 });

  return NextResponse.json({ ticket });
}

/** The institution may close its own ticket (e.g. after the solution worked). */
export async function PATCH(_req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const ticket = await prisma.supportTicket.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true, status: true },
  });
  if (!ticket) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (ticket.status === "CLOSED") {
    return NextResponse.json({ error: "TICKET_CLOSED" }, { status: 409 });
  }

  const updated = await prisma.supportTicket.update({
    where: { id: ticket.id },
    data: { status: "CLOSED" },
  });
  return NextResponse.json({ ticket: updated });
}
