export const prerender = false;

import type { APIRoute } from 'astro';
import { readFile, stat } from 'node:fs/promises';
import { join, resolve, extname } from 'node:path';

const UPLOADS_ROOT = resolve(process.cwd(), 'data', 'uploads');

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

export const GET: APIRoute = async ({ params }) => {
  const rawPath = (params.path as string | undefined) ?? '';
  if (!rawPath) {
    return new Response('not found', { status: 404 });
  }

  const target = resolve(join(UPLOADS_ROOT, rawPath));
  if (!target.startsWith(UPLOADS_ROOT + '/') && target !== UPLOADS_ROOT) {
    return new Response('forbidden', { status: 403 });
  }

  try {
    const stats = await stat(target);
    if (!stats.isFile()) {
      return new Response('not found', { status: 404 });
    }
  } catch {
    return new Response('not found', { status: 404 });
  }

  const ext = extname(target).toLowerCase();
  const type = MIME[ext] ?? 'application/octet-stream';
  const buffer = await readFile(target);

  return new Response(buffer, {
    headers: {
      'Content-Type': type,
      'Content-Length': String(buffer.length),
      'Cache-Control': 'public, max-age=300, must-revalidate',
    },
  });
};
