import { readFile } from "fs/promises";
import path from "path";
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { canManageHumanCapital } from "@/lib/human-capital";

const HUMAN_CAPITAL_FILES_UPLOAD_DIR =
  process.env.HUMAN_CAPITAL_FILES_UPLOAD_DIR?.trim() || "/tmp/casa-benell/uploads/human-capital-files";

function resolveFilePath(filename: string): string | null {
  const normalized = filename.trim();
  if (!normalized || normalized.includes("/") || normalized.includes("\\")) {
    return null;
  }

  const base = path.resolve(HUMAN_CAPITAL_FILES_UPLOAD_DIR);
  const target = path.resolve(base, normalized);
  if (target !== base && !target.startsWith(`${base}${path.sep}`)) {
    return null;
  }

  return target;
}

function contentTypeForFile(filename: string): string {
  const lower = filename.toLowerCase();
  if (lower.endsWith(".pdf")) {
    return "application/pdf";
  }
  if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) {
    return "image/jpeg";
  }
  if (lower.endsWith(".png")) {
    return "image/png";
  }
  if (lower.endsWith(".webp")) {
    return "image/webp";
  }
  if (lower.endsWith(".doc")) {
    return "application/msword";
  }
  if (lower.endsWith(".docx")) {
    return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
  }
  if (lower.endsWith(".xls")) {
    return "application/vnd.ms-excel";
  }
  if (lower.endsWith(".xlsx")) {
    return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  }
  if (lower.endsWith(".txt")) {
    return "text/plain; charset=utf-8";
  }
  return "application/octet-stream";
}

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

  if (!canManageHumanCapital(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owner/HC leaders can access files." }, { status: 403 });
  }

  const absolutePath = resolveFilePath(context.params.filename);
  if (!absolutePath) {
    return NextResponse.json({ error: "Invalid filename." }, { status: 400 });
  }

  try {
    const content = await readFile(absolutePath);
    return new Response(content, {
      status: 200,
      headers: {
        "Content-Type": contentTypeForFile(context.params.filename),
        "Content-Length": String(content.byteLength),
        "Cache-Control": "private, no-store",
      },
    });
  } catch {
    return NextResponse.json({ error: "File not found." }, { status: 404 });
  }
}
