import { NextRequest, NextResponse } from "next/server";
import { readFile } from "fs/promises";
import { connectDB } from "@/lib/db";
import { Order } from "@/models/Order";
import { getSessionClientId } from "@/lib/auth";
import { hasPermission } from "@/lib/adminAuth";
import { orderUploadPath } from "@/lib/uploads";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ orderId: string; filename: string }> }
) {
  const { orderId, filename } = await params;
  const [clientId, isAdmin] = await Promise.all([getSessionClientId(), hasPermission("orders_view")]);
  if (!clientId && !isAdmin) return new NextResponse("Unauthorized", { status: 401 });

  await connectDB();
  const order = await Order.findById(orderId).lean();
  // Der Besitzer darf seine eigenen Anhänge abrufen, der Admin alle.
  if (!order || (!isAdmin && String(order.clientId) !== clientId)) {
    return new NextResponse("Not found", { status: 404 });
  }

  const attachment = order.attachments.find((a) => a.storedName === filename);
  if (!attachment) return new NextResponse("Not found", { status: 404 });

  try {
    const buffer = await readFile(orderUploadPath(orderId, filename));
    return new NextResponse(new Uint8Array(buffer), {
      headers: {
        "Content-Type": attachment.mimeType,
        "Content-Disposition": `inline; filename="${encodeURIComponent(attachment.filename)}"`,
        "Cache-Control": "private, max-age=0, no-store",
      },
    });
  } catch {
    return new NextResponse("Not found", { status: 404 });
  }
}
