import type { APIRoute } from "astro";
import path from "node:path";
import fs from "node:fs/promises";
import { UPLOADS_DIR } from "../../lib/article-store";

export const prerender = false;

const MIME_TYPES: Record<string, string> = {
  ".png": "image/png",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".webp": "image/webp",
  ".gif": "image/gif",
};

export const GET: APIRoute = async ({ params }) => {
  const filename = params.file || "";
  if (!/^[a-zA-Z0-9._-]+$/.test(filename)) return new Response("Not Found", { status: 404 });
  try {
    const content = await fs.readFile(path.join(UPLOADS_DIR, filename));
    return new Response(content, {
      headers: {
        "Content-Type": MIME_TYPES[path.extname(filename).toLowerCase()] || "application/octet-stream",
        "Cache-Control": "public, max-age=31536000, immutable",
      },
    });
  } catch {
    return new Response("Not Found", { status: 404 });
  }
};
