import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { readPdf } from "@/lib/storage";

export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await auth();
  if (!session?.user) {
    return NextResponse.json({ error: "Non authentifié." }, { status: 401 });
  }

  const { id } = await params;
  const bilan = await prisma.bilan.findUnique({ where: { id } });
  if (!bilan || !bilan.pdfUrl) {
    return NextResponse.json({ error: "Introuvable." }, { status: 404 });
  }

  const isOwner = session.user.role === "PHARMACY" && session.user.pharmacyId === bilan.pharmacyId;
  const isAdmin = session.user.role === "ADMIN";
  if (!isOwner && !isAdmin) {
    return NextResponse.json({ error: "Accès refusé." }, { status: 403 });
  }

  const buffer = await readPdf(bilan.pdfUrl);
  return new NextResponse(new Uint8Array(buffer), {
    headers: {
      "content-type": "application/pdf",
      "content-disposition": `inline; filename="bilan-prevention-${bilan.id}.pdf"`,
    },
  });
}
