import { readFile } from "node:fs/promises";
import { NextResponse } from "next/server";
import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";
import { getCloudScope, canReadFile } from "@/lib/cloud/access";
import { cloudPath, isSafeCloudName, isInlineSafe } from "@/lib/cloud/storage";

/**
 * Liefert eine Cloud-Datei aus — nur für Berechtigte.
 *
 * Sicherheitsentscheidung: Angezeigt (`inline`) werden ausschließlich Typen,
 * die keinen Code ausführen können. Alles andere — insbesondere SVG und HTML —
 * wird als Download ausgeliefert, sonst ließe sich über eine hochgeladene
 * Datei Skriptcode im Kontext der Anwendung ausführen.
 */
export async function GET(
  req: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await auth();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const file = await prisma.cloudFile.findUnique({
    where: { id },
    select: {
      id: true,
      name: true,
      mime: true,
      storedName: true,
      folderId: true,
      ownerId: true,
    },
  });
  if (!file || !isSafeCloudName(file.storedName)) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  const scope = await getCloudScope(session.user.id);
  if (!canReadFile(scope, file)) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  let data: Buffer;
  try {
    data = await readFile(cloudPath(file.storedName));
  } catch {
    return NextResponse.json({ error: "Datei fehlt auf dem Server." }, { status: 404 });
  }

  const wantsDownload = new URL(req.url).searchParams.get("download") === "1";
  const inline = !wantsDownload && isInlineSafe(file.mime);
  const safeName = file.name.replace(/["\r\n]/g, "");

  return new Response(new Uint8Array(data), {
    headers: {
      "Content-Type": inline ? file.mime : "application/octet-stream",
      "Content-Disposition": `${inline ? "inline" : "attachment"}; filename="${safeName}"`,
      "Cache-Control": "private, max-age=300",
      "X-Content-Type-Options": "nosniff",
    },
  });
}
