import { NextResponse } from 'next/server';

export async function POST(request: Request) {
    try {
        const formData = await request.formData();
        const file = formData.get('file') as File | null;

        if (!file) {
            return NextResponse.json({ error: 'No file provided' }, { status: 400 });
        }

        const apiKey = process.env.RED_IMAGE_API_KEY;
        if (!apiKey) {
            return NextResponse.json({ error: 'Server misconfiguration: No RED API Key' }, { status: 500 });
        }

        // RED image host requires 'file' POST argument for local file upload
        const upstreamFormData = new FormData();
        upstreamFormData.append('file', file);

        const response = await fetch('https://redacted.sh/ajax.php?action=upload_image', {
            method: 'POST',
            headers: {
                'Authorization': apiKey,
            },
            body: upstreamFormData,
        });

        if (!response.ok) {
            throw new Error(`Upload failed with status: ${response.status}`);
        }

        const data = await response.json();

        if (data.status !== 'success' || !data.response || !data.response.url) {
            throw new Error(data.error || data.status || 'Invalid response from RED image host');
        }

        const imageUrl = data.response.url;

        return NextResponse.json({ url: imageUrl });

    } catch (error) {
        console.error('RED image host upload error:', error);
        const errorMessage = error instanceof Error ? error.message : 'Internal Server Error';
        return NextResponse.json({ error: errorMessage }, { status: 500 });
    }
}