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

const ALLOWED: Record<string, string> = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.gif': 'image/gif' };
const MAX_BYTES = 5 * 1024 * 1024;

const json = (status: number, body: object) =>
  new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });

export const POST: APIRoute = async ({ request }) => {
  const form = await request.formData().catch(() => null);
  const file = form?.get('file');
  if (!(file instanceof File)) return json(400, { error: 'Nessun file.' });
  const ext = extname(file.name).toLowerCase();
  if (!ALLOWED[ext]) return json(400, { error: 'Formato non consentito (jpg, png, webp, gif).' });
  if (file.size > MAX_BYTES) return json(400, { error: 'File troppo grande (max 5 MB).' });
  const dir = getEnv('UPLOADS_DIR', 'uploads');
  await mkdir(dir, { recursive: true });
  const name = `${Date.now()}-${randomBytes(4).toString('hex')}${ext}`;
  await writeFile(join(dir, name), Buffer.from(await file.arrayBuffer()));
  return json(200, { url: `/uploads/${name}` });
};
