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

function getUploadDir(): string {
    // Docker: /app/screenshots (mounted volume)
    if (fs.existsSync('/app/screenshots')) return '/app/screenshots';
    // Dev: platform/screenshots (relative to project)
    const devPath = '/media/yusiboyz/Media/Scripts/platform/screenshots';
    if (!fs.existsSync(devPath)) fs.mkdirSync(devPath, { recursive: true });
    return devPath;
}

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

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

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

        const uploadDir = getUploadDir();
        const fullPath = path.join(uploadDir, filename);
        fs.writeFileSync(fullPath, buffer);

        console.log(`Screenshot saved: ${fullPath} (${buffer.length} bytes)`);
        return json({ ok: true, filename, size: buffer.length });
    } catch (err: any) {
        console.error('Upload failed:', err);
        return json({ error: err.message || 'Upload failed' }, { status: 500 });
    }
};
