import { NextResponse } from "next/server";
import { createReadStream, existsSync, statSync } from "fs";
import { extname, join } from "path";

// Manually map extensions to MIME types
const mimeTypes = {
  ".pdf": "application/pdf",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".png": "image/png",
  ".webp": "image/webp",
  ".gif": "image/gif",
  ".doc": "application/msword",
  ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  ".xls": "application/vnd.ms-excel",
  ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
};

export async function GET(req, { params }) {
  const { slug } = params;
  const relativeFilePath = slug.join("/");

  const baseDir = join(process.cwd(), "uploads");
  const filePath = join(baseDir, relativeFilePath);

  if (!existsSync(filePath)) {
    return new NextResponse("File not found", { status: 404 });
  }

  const fileStat = statSync(filePath);
  const fileStream = createReadStream(filePath);

  // Get extension and MIME type
  const ext = extname(filePath).toLowerCase();
  const contentType = mimeTypes[ext] || "application/octet-stream";

  // Define viewable types (others will download)
  const viewableTypes = [
    "application/pdf",
    "image/jpeg",
    "image/png",
    "image/webp",
    "image/gif",
  ];

  const isViewable = viewableTypes.includes(contentType);

  return new NextResponse(fileStream, {
    status: 200,
    headers: {
      "Content-Type": contentType,
      "Content-Length": fileStat.size,
      "Content-Disposition": `${isViewable ? "inline" : "attachment"}; filename="${slug.at(-1)}"`,
    },
  });
}
