import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import { env } from "@/env";

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const source = searchParams.get("source");
  const filePath = searchParams.get("path");

  if (!source || !filePath) {
    return new NextResponse("Missing source or path", { status: 400 });
  }

  let baseDir: string | undefined;
  if (source === "zxdb") {
    baseDir = env.ZXDB_LOCAL_FILEPATH;
  } else if (source === "wos") {
    baseDir = env.WOS_LOCAL_FILEPATH;
  }

  if (!baseDir) {
    return new NextResponse("Invalid source or mirroring not enabled", { status: 400 });
  }

  // Defense-in-depth: reject obvious traversal before joining
  if (filePath.includes("..")) {
    return new NextResponse("Forbidden", { status: 403 });
  }

  // Security: Ensure path doesn't escape baseDir
  const absolutePath = path.normalize(path.join(baseDir, filePath));
  if (!absolutePath.startsWith(path.normalize(baseDir))) {
    return new NextResponse("Forbidden", { status: 403 });
  }

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

  const stat = fs.statSync(absolutePath);
  if (!stat.isFile()) {
    return new NextResponse("Not a file", { status: 400 });
  }

  const fileBuffer = fs.readFileSync(absolutePath);
  const fileName = path.basename(absolutePath);
  const ext = path.extname(fileName).toLowerCase();

  // Determine Content-Type
  let contentType = "application/octet-stream";
  if (ext === ".txt" || ext === ".nfo") {
    contentType = "text/plain; charset=utf-8";
  } else if (ext === ".png") {
    contentType = "image/png";
  } else if (ext === ".jpg" || ext === ".jpeg") {
    contentType = "image/jpeg";
  } else if (ext === ".gif") {
    contentType = "image/gif";
  } else if (ext === ".pdf") {
    contentType = "application/pdf";
  }

  const isView = searchParams.get("view") === "1";
  const disposition = isView ? "inline" : "attachment";

  return new NextResponse(fileBuffer, {
    headers: {
      "Content-Type": contentType,
      "Content-Disposition": `${disposition}; filename="${fileName}"`,
      "Content-Length": stat.size.toString(),
    },
  });
}

export const runtime = "nodejs";
