export const prerender = false;

import type { APIRoute } from 'astro';
import { writeFile, mkdir } from 'node:fs/promises';
import { join, extname, basename } from 'node:path';

const UPLOAD_DIR = join(process.cwd(), 'public', 'img');
const ALLOWED_EXT = new Set(['.png', '.jpg', '.jpeg', '.webp', '.svg', '.gif']);

function sanitize(filename: string): string {
  const name = basename(filename).replace(/[^a-zA-Z0-9._-]/g, '_');
  return name.slice(-120);
}

export const POST: APIRoute = async ({ request }) => {
  const form = await request.formData();
  const file = form.get('file');
  const folder = (form.get('folder') as string | null) ?? '';

  if (!(file instanceof File)) {
    return new Response(JSON.stringify({ error: 'no_file' }), { status: 400 });
  }

  const ext = extname(file.name).toLowerCase();
  if (!ALLOWED_EXT.has(ext)) {
    return new Response(JSON.stringify({ error: 'invalid_extension' }), { status: 400 });
  }

  const safeFolder = folder.replace(/[^a-zA-Z0-9_-]/g, '');
  const targetDir = safeFolder ? join(UPLOAD_DIR, safeFolder) : UPLOAD_DIR;
  await mkdir(targetDir, { recursive: true });

  const filename = sanitize(file.name);
  const buffer = Buffer.from(await file.arrayBuffer());
  await writeFile(join(targetDir, filename), buffer);

  const url = `/img/${safeFolder ? safeFolder + '/' : ''}${filename}`;
  return new Response(JSON.stringify({ ok: true, url }), {
    headers: { 'Content-Type': 'application/json' },
  });
};
