/* ---------------------------------------------------------------------------
 * POST /api/admin/upload — fenja-only event photo upload.
 *
 * Accepts multipart/form-data with a single `file` (png/jpg, ≤5 MB), writes it
 * to the upload dir under a random name, and returns { url } pointing at the
 * /uploads/[file] serve route. The caller (admin image-upload field) stores
 * that url in the event's photo_url.
 * ------------------------------------------------------------------------- */

import type { APIRoute } from 'astro';
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { UPLOAD_DIR, ALLOWED_IMAGE_TYPES, MAX_UPLOAD_BYTES } from '../../../lib/uploads';

export const prerender = false;

function json(body: unknown, status: number): Response {
  return new Response(JSON.stringify(body), {
    status,
    headers: { 'Content-Type': 'application/json' },
  });
}

export const POST: APIRoute = async ({ locals, request }) => {
  if (locals.user?.role !== 'fenja') return json({ error: 'Forbidden' }, 403);

  let form: FormData;
  try {
    form = await request.formData();
  } catch {
    return json({ error: 'Expected multipart form data.' }, 400);
  }

  const file = form.get('file');
  if (!(file instanceof File) || file.size === 0) {
    return json({ error: 'No file provided.' }, 400);
  }

  const ext = ALLOWED_IMAGE_TYPES.get(file.type);
  if (!ext) return json({ error: 'Only PNG or JPG images are allowed.' }, 415);
  if (file.size > MAX_UPLOAD_BYTES) {
    return json({ error: 'Image must be 5 MB or smaller.' }, 413);
  }

  const name = `${randomUUID()}.${ext}`;
  try {
    await mkdir(UPLOAD_DIR, { recursive: true });
    await writeFile(join(UPLOAD_DIR, name), Buffer.from(await file.arrayBuffer()));
  } catch {
    return json({ error: 'Could not save the image. Try again.' }, 500);
  }

  return json({ url: `/uploads/${name}` }, 200);
};
