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

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 pharmacy = await prisma.pharmacy.findUnique({ where: { id } });
  if (!pharmacy || !pharmacy.qrCodeUrl) {
    return NextResponse.json({ error: "Introuvable." }, { status: 404 });
  }

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

  const buffer = await readQrCode(pharmacy.qrCodeUrl);
  return new NextResponse(new Uint8Array(buffer), {
    headers: {
      "content-type": "image/png",
      "content-disposition": `inline; filename="qr-${pharmacy.slug}.png"`,
    },
  });
}
