import { NextRequest, NextResponse } from 'next/server';
import { WhiskClient } from '@/lib/whisk-client';

export async function POST(req: NextRequest) {
    try {
        const { prompt, imageBase64, imageGenerationId, cookies: clientCookies } = await req.json();

        if (!prompt) {
            return NextResponse.json({ error: 'Missing prompt' }, { status: 400 });
        }

        // Get cookies from request or use provided cookies
        const cookieString = clientCookies || req.cookies.get('whisk_cookies')?.value;

        if (!cookieString) {
            return NextResponse.json(
                { error: "Whisk cookies not found. Please configure settings." },
                { status: 401 }
            );
        }

        console.log(`[Video API] Generating video for prompt: "${prompt.substring(0, 50)}..."`);

        const client = new WhiskClient(cookieString);

        // Generate video using WhiskClient
        // Pass imageGenerationId if available, otherwise pass base64 to upload first
        const result = await client.generateVideo(
            imageGenerationId || '',
            prompt,
            imageBase64
        );

        return NextResponse.json({
            success: true,
            id: result.id,
            url: result.url,
            status: result.status
        });

    } catch (error: any) {
        console.error("Video Generation API failed:", error);
        return NextResponse.json({
            error: error.message || 'Video generation failed'
        }, { status: 500 });
    }
}
