/* ---------------------------------------------------------------------------
 * GET /uploads/[file] — serve an uploaded event photo from the upload dir.
 *
 * Runtime-written files live outside the build output, so they're streamed
 * here rather than served as static assets. Gated by the global auth
 * middleware (viewers are logged in; the <img> request carries the session
 * cookie). Filename is validated to prevent path traversal.
 * ------------------------------------------------------------------------- */

import type { APIRoute } from 'astro';
import { readFile } from 'node:fs/promises';
import { join, extname } from 'node:path';
import { UPLOAD_DIR, isSafeUploadName, UPLOAD_CONTENT_TYPES } from '../../lib/uploads';

export const prerender = false;

export const GET: APIRoute = async ({ params }) => {
  const file = params.file ?? '';
  if (!isSafeUploadName(file)) return new Response('Not found', { status: 404 });

  const type = UPLOAD_CONTENT_TYPES[extname(file).toLowerCase()];
  if (!type) return new Response('Not found', { status: 404 });

  try {
    const buf = await readFile(join(UPLOAD_DIR, file));
    return new Response(new Uint8Array(buf), {
      headers: {
        'Content-Type': type,
        'Cache-Control': 'public, max-age=31536000, immutable',
      },
    });
  } catch {
    return new Response('Not found', { status: 404 });
  }
};
