import sharp from 'sharp';

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

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

    // Form alanlarından parametreleri al
    const getField = (name: string) => {
        const field = files.find(f => f.name === name);
        return field ? field.data.toString() : null;
    };

    const format = getField('format') || 'avif';
    const quality = parseInt(getField('quality') || '85', 10);
    const width = getField('width') ? parseInt(getField('width')!, 10) : null;
    const height = getField('height') ? parseInt(getField('height')!, 10) : null;

    try {
        let pipeline = sharp(file.data);

        // Resize işlemi (en veya boy varsa)
        if (width || height) {
            pipeline = pipeline.resize(width, height, { fit: 'cover' });
        }

        // Format ve kalite ayarı
        if (format === 'avif') {
            pipeline = pipeline.avif({ quality });
        } else if (format === 'webp') {
            pipeline = pipeline.webp({ quality });
        } else if (format === 'png') {
            pipeline = pipeline.png({ quality });
        } else if (format === 'jpeg' || format === 'jpg') {
            pipeline = pipeline.jpeg({ quality });
        } else {
            // Varsayılan avif
            pipeline = pipeline.avif({ quality });
        }

        const optimizedBuffer = await pipeline.toBuffer();

        // Content-Type i ayarla
        let contentType = 'image/avif';
        if (format === 'webp') contentType = 'image/webp';
        if (format === 'png') contentType = 'image/png';
        if (format === 'jpeg' || format === 'jpg') contentType = 'image/jpeg';

        setResponseHeader(event, 'Content-Type', contentType);
        return optimizedBuffer;
    } catch (error) {
        console.error('Resim optimizasyonu hatası:', error);
        throw createError({ statusCode: 500, statusMessage: 'Resim optimize edilemedi' });
    }
});
