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

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

const STATUSES = ["OPEN", "IN_PROGRESS", "RESOLVED", "CLOSED"] as const;
type Status = (typeof STATUSES)[number];

/** Ticket detail for the support panel: institution, conversation, attachment meta. */
export async function GET(_req: Request, { params }: Params) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const ticket = await prisma.supportTicket.findFirst({
    where: { id: Number(id) },
    include: {
      institution: { select: { id: true, name: true, type: true, email: true, phone: true } },
      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 });
}

/** Change the ticket status: { status: OPEN | IN_PROGRESS | RESOLVED | CLOSED }. */
export async function PATCH(req: Request, { params }: Params) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

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

  try {
    const body = await req.json();
    const status = String(body.status ?? "");
    if (!STATUSES.includes(status as Status)) {
      return NextResponse.json({ error: "Invalid status" }, { status: 400 });
    }
    const updated = await prisma.supportTicket.update({
      where: { id: ticket.id },
      data: { status: status as Status },
    });
    return NextResponse.json({ ticket: updated });
  } catch {
    return NextResponse.json({ error: "Could not update ticket" }, { status: 500 });
  }
}
