import { readFile } from "fs/promises";
import path from "path";
import { NextResponse } from "next/server";

import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";

export const runtime = "nodejs";

function getUploadPath(attachmentId: string) {
  const uploadDir = path.resolve(
    process.env.UPLOAD_DIR ?? "uploads",
    "announcements",
  );
  return path.join(uploadDir, attachmentId);
}

function contentDisposition(fileName: string) {
  const fallback = fileName.replace(/[^\w.\-]/g, "_");
  return `inline; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(fileName)}`;
}

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await auth();
  const user = session?.user;

  if (!user?.id || !user.kitaId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const attachment = await prisma.attachment.findFirst({
    where: {
      id,
      announcement: {
        kitaId: user.kitaId,
      },
    },
    select: {
      id: true,
      fileName: true,
      fileType: true,
    },
  });

  if (!attachment) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  try {
    const file = await readFile(getUploadPath(attachment.id));
    return new Response(new Uint8Array(file), {
      headers: {
        "Content-Type": attachment.fileType,
        "Content-Disposition": contentDisposition(attachment.fileName),
        "Cache-Control": "private, max-age=300",
      },
    });
  } catch (error) {
    console.error("Anhang konnte nicht gelesen werden:", error);
    return NextResponse.json({ error: "File not found" }, { status: 404 });
  }
}
