import { readFile } from "fs/promises";
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
  canAccessExperienciometro,
  ensureExperienceBaseline,
  resolveExperienceStoragePath,
} from "@/lib/experienciometro";

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 });
  }

  if (!canAccessExperienciometro(session.user.role)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  await ensureExperienceBaseline(prisma, session.user.id);

  const record = await prisma.experienceEvidence.findUnique({
    where: { id: context.params.id },
    select: {
      id: true,
      title: true,
      storagePath: true,
      mimeType: true,
    },
  });

  if (!record || !record.storagePath) {
    return NextResponse.json({ error: "Asset not found." }, { status: 404 });
  }

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

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

    return new Response(content, {
      status: 200,
      headers: {
        "Content-Type": record.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 });
  }
}
