import { NextResponse } from "next/server";

// Serves the profile picture through our own origin, caching the bytes in
// process memory so we don't hit the upstream CDN on every request.

const DEFAULT_IMAGE = "https://cdn.reversed.dev/pictures/20250405_120402.png";
const CACHE_TTL_MS = 1000 * 60 * 60; // 1 hour

type ImageCache = { body: ArrayBuffer; contentType: string; expiresAt: number };
let cached: ImageCache | null = null;

async function loadImage(): Promise<ImageCache | null> {
  if (cached && cached.expiresAt > Date.now()) return cached;

  const source = process.env.PROFILE_IMAGE_URL || DEFAULT_IMAGE;
  try {
    const res = await fetch(source, { signal: AbortSignal.timeout(8000) });
    if (!res.ok) return cached; // fall back to stale copy if present
    const body = await res.arrayBuffer();
    cached = {
      body,
      contentType: res.headers.get("content-type") || "image/png",
      expiresAt: Date.now() + CACHE_TTL_MS,
    };
    return cached;
  } catch {
    return cached;
  }
}

export async function GET() {
  const image = await loadImage();
  if (!image) {
    return NextResponse.json({ error: "Image unavailable" }, { status: 502 });
  }

  return new NextResponse(image.body, {
    headers: {
      "Content-Type": image.contentType,
      "Cache-Control": "public, max-age=3600, stale-while-revalidate=86400",
    },
  });
}
