import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import fs from 'fs';
import path from 'path';

const UPLOAD_DIR = '/app/screenshots';

export const POST: RequestHandler = async ({ request }) => {
    const formData = await request.formData();
    const file = formData.get('file') as File;
    if (!file) return json({ error: 'No file' }, { status: 400 });

    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
    const ext = file.name.split('.').pop() || 'png';
    const filename = `${timestamp}.${ext}`;

    const buffer = Buffer.from(await file.arrayBuffer());

    // Ensure directory exists
    if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR, { recursive: true });

    fs.writeFileSync(path.join(UPLOAD_DIR, filename), buffer);

    return json({ ok: true, filename, path: `/app/screenshots/${filename}` });
};
