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

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 checked = validateUploadFile(form?.get('file'));
  if (!checked.ok) return json(400, { error: checked.error });
  const dir = getEnv('UPLOADS_DIR', 'uploads');
  await mkdir(dir, { recursive: true });
  const name = `${Date.now()}-${randomBytes(4).toString('hex')}${checked.ext}`;
  await writeFile(join(dir, name), Buffer.from(await checked.file.arrayBuffer()));
  return json(200, { url: `/uploads/${name}` });
};
