import type { APIRoute } from 'astro';
import { readFile } from 'node:fs/promises';
import { join, normalize, extname } from 'node:path';
import { getEnv } from '../../lib/env';
export const prerender = false;

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

export const GET: APIRoute = async ({ params }) => {
  const rel = normalize(params.path ?? '').replace(/^(\.\.[/\\])+/, '');
  if (!rel || rel.includes('..')) return new Response('Not found', { status: 404 });
  const mime = MIME[extname(rel).toLowerCase()];
  if (!mime) return new Response('Not found', { status: 404 });
  try {
    const buf = await readFile(join(getEnv('UPLOADS_DIR', 'uploads'), rel));
    return new Response(buf, { headers: { 'Content-Type': mime, 'Cache-Control': 'public, max-age=31536000, immutable' } });
  } catch {
    return new Response('Not found', { status: 404 });
  }
};
