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

const ACCOUNT_AVATAR_UPLOAD_DIR = process.env.ACCOUNT_AVATAR_UPLOAD_DIR?.trim() || "/tmp/casa-benell/uploads/avatars";

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

  const base = path.resolve(ACCOUNT_AVATAR_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 {
  if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
    return "image/jpeg";
  }

  if (filename.endsWith(".png")) {
    return "image/png";
  }

  if (filename.endsWith(".webp")) {
    return "image/webp";
  }

  return "application/octet-stream";
}

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

  const absolutePath = resolveAvatarPath(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.toLowerCase()),
        "Content-Length": String(content.byteLength),
        "Cache-Control": "private, no-store",
      },
    });
  } catch {
    return NextResponse.json({ error: "Avatar not found." }, { status: 404 });
  }
}
