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

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

/** Download a support-ticket attachment. SUPER_ADMIN can fetch any; an
    INSTITUTION_ADMIN only attachments of its own tickets. */
export async function GET(_req: Request, { params }: Params) {
  const session = await getSession();
  if (!session || (session.role !== "SUPER_ADMIN" && session.role !== "INSTITUTION_ADMIN")) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const attachment = await prisma.supportTicketAttachment.findFirst({
    where: {
      id: Number(id),
      ...(session.role === "INSTITUTION_ADMIN" ? { ticket: { institutionId: session.institutionId! } } : {}),
    },
    select: { fileName: true, mimeType: true, data: true },
  });
  if (!attachment) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const buffer = Buffer.from(attachment.data, "base64");
  const asciiName = attachment.fileName.replace(/[^\x20-\x7E]/g, "_").replace(/"/g, "");
  return new NextResponse(new Uint8Array(buffer), {
    headers: {
      "Content-Type": attachment.mimeType || "application/octet-stream",
      "Content-Length": String(buffer.length),
      "Content-Disposition": `attachment; filename="${asciiName}"; filename*=UTF-8''${encodeURIComponent(attachment.fileName)}`,
    },
  });
}
