import { readFile } from "fs/promises";
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { canAccessEvidence, getCaptureEvidenceById, resolveCaptureStoragePath } from "@/lib/capture";

export async function GET(_request: Request, context: { params: { id: string } }) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const evidence = await getCaptureEvidenceById({ id: context.params.id });
  if (!evidence || !evidence.storagePath) {
    return NextResponse.json({ error: "Asset not found." }, { status: 404 });
  }

  if (
    !canAccessEvidence(
      {
        userId: session.user.id,
        role: session.user.role,
        department: session.user.department ?? null,
      },
      {
        department: evidence.department,
        ownerUserId: evidence.catalog?.ownerUserId ?? null,
        uploadedById: evidence.uploadedById,
      }
    )
  ) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const absolutePath = resolveCaptureStoragePath(evidence.storagePath);
  if (!absolutePath) {
    return NextResponse.json({ error: "Invalid storage path." }, { status: 500 });
  }

  try {
    const content = await readFile(absolutePath);
    const safeName = evidence.title.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 64) || "evidence";

    return new Response(content, {
      status: 200,
      headers: {
        "Content-Type": evidence.mimeType || "application/octet-stream",
        "Content-Length": String(content.byteLength),
        "Content-Disposition": `inline; filename="${safeName}"`,
        "Cache-Control": "private, max-age=60",
      },
    });
  } catch {
    return NextResponse.json({ error: "Asset file not found." }, { status: 404 });
  }
}
