import { NextRequest, NextResponse } from "next/server";
import { readFile } from "fs/promises";
import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { getSessionClientId } from "@/lib/auth";
import { avatarUploadPath } from "@/lib/uploads";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ clientId: string; filename: string }> }
) {
  const { clientId, filename } = await params;
  const viewerId = await getSessionClientId();
  if (!viewerId) return new NextResponse("Unauthorized", { status: 401 });

  await connectDB();
  const client = await Client.findById(clientId).lean();
  if (!client || client.avatarPath !== filename) return new NextResponse("Not found", { status: 404 });

  try {
    const buffer = await readFile(avatarUploadPath(clientId, filename));
    const ext = filename.split(".").pop()?.toLowerCase();
    const mimeType = ext === "png" ? "image/png" : ext === "webp" ? "image/webp" : "image/jpeg";
    return new NextResponse(new Uint8Array(buffer), {
      headers: { "Content-Type": mimeType, "Cache-Control": "private, max-age=3600" },
    });
  } catch {
    return new NextResponse("Not found", { status: 404 });
  }
}
