import sharp from 'sharp';
import { promises as fs } from 'fs';
import path from 'path';

export default defineEventHandler(async (event) => {
    // Ensure user is admin
    // Note: Assuming global middleware or checking specific context/auth here if strict security is needed.
    // For now, relying on the fact that this is used within Admin context.

    const files = await readMultipartFormData(event);
    if (!files || files.length === 0) {
        throw createError({ statusCode: 400, statusMessage: 'Dosya yüklenmedi' });
    }

    const file = files.find(f => f.name === 'file');
    if (!file || !file.filename) {
        throw createError({ statusCode: 400, statusMessage: 'Geçersiz dosya' });
    }

    // Check file type
    const validTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/avif', 'image/gif'];
    if (!validTypes.includes(file.type || '')) {
        throw createError({ statusCode: 400, statusMessage: 'Sadece resim dosyaları yüklenebilir (jpeg, png, webp, avif, gif)' });
    }

    try {
        const uploadDir = path.join(process.cwd(), 'public', 'uploads');

        // Ensure directory exists
        try {
            await fs.access(uploadDir);
        } catch {
            await fs.mkdir(uploadDir, { recursive: true });
        }

        const ext = path.extname(file.filename);
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const filename = 'avatar-' + uniqueSuffix + ext; // Keeping original extension for simplicity unless converting
        const filepath = path.join(uploadDir, filename);

        // Process with Sharp (Optional: Resize to max 800x800 for avatars to save space)
        await sharp(file.data)
            .resize(800, 800, {
                fit: 'inside',
                withoutEnlargement: true
            })
            .toFile(filepath);

        return {
            url: '/uploads/' + filename,
            message: 'Dosya başarıyla yüklendi'
        };

    } catch (error) {
        console.error('Upload error:', error);
        throw createError({ statusCode: 500, statusMessage: 'Dosya yüklenemedi' });
    }
});
