import { NextRequest, NextResponse } from 'next/server';
import { sendSellFurnitureEmail } from '@/lib/email';

export async function POST(req: NextRequest) {
    try {
        const formData = await req.formData();

        const name = formData.get('name') as string;
        const email = formData.get('email') as string;
        const phone = formData.get('phone') as string;
        const address = formData.get('address') as string;
        const message = formData.get('message') as string;

        // Validation
        if (!name || !email || !phone || !address || !message) {
            return NextResponse.json(
                { error: 'Alla fält är obligatoriska' },
                { status: 400 }
            );
        }

        // Email validation
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return NextResponse.json(
                { error: 'Ogiltig e-postadress' },
                { status: 400 }
            );
        }

        // Get uploaded images
        const images: { filename: string; content: Buffer; contentType: string }[] = [];
        const imageFiles = formData.getAll('images');

        if (imageFiles.length > 4) {
            return NextResponse.json(
                { error: 'Max 4 bilder tillåtna' },
                { status: 400 }
            );
        }

        for (const file of imageFiles) {
            if (file instanceof File) {
                // Validate file type
                if (!file.type.startsWith('image/')) {
                    return NextResponse.json(
                        { error: 'Endast bildfiler tillåtna' },
                        { status: 400 }
                    );
                }

                // Validate file size (max 5MB per image)
                if (file.size > 5 * 1024 * 1024) {
                    return NextResponse.json(
                        { error: 'Bilderna får max vara 5MB vardera' },
                        { status: 400 }
                    );
                }

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

                images.push({
                    filename: file.name,
                    content: buffer,
                    contentType: file.type
                });
            }
        }

        // Send email with attachments
        const success = await sendSellFurnitureEmail(
            name,
            email,
            phone,
            address,
            message,
            images
        );

        if (!success) {
            return NextResponse.json(
                { error: 'Kunde inte skicka meddelandet. Försök igen senare.' },
                { status: 500 }
            );
        }

        return NextResponse.json(
            { message: 'Tack! Vi återkommer så snart vi kan.' },
            { status: 200 }
        );
    } catch (error) {
        console.error('Sell furniture form error:', error);
        return NextResponse.json(
            { error: 'Ett oväntat fel uppstod' },
            { status: 500 }
        );
    }
}
