import { NextResponse } from 'next/server';
import { v0 } from 'v0-sdk';

export async function POST(request: Request) {
  try {
    const { prompt, style, projectId } = await request.json();

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

    // Check for API key
    const apiKey = process.env.V0_API_KEY;
    if (!apiKey) {
      return NextResponse.json(
        { error: 'V0_API_KEY not configured' },
        { status: 500 }
      );
    }

    // Create system message based on style
    const styleInstructions: Record<string, string> = {
      modern: 'Create a modern, sleek design with clean lines and contemporary aesthetics',
      minimal: 'Create a minimal, clean design with lots of whitespace and simple elements',
      colorful: 'Create a vibrant, colorful design with bold colors and energetic feel',
      dark: 'Create a dark mode design with dark backgrounds and light text',
      glassmorphism: 'Create a glassmorphism design with frosted glass effects and transparency',
    };

    const styleInstruction = style && styleInstructions[style] 
      ? styleInstructions[style]
      : 'Create a modern, professional design';

    const systemMessage = `You are an expert React and Tailwind CSS developer. ${styleInstruction}. Use Next.js conventions and best practices. Make it responsive and accessible.`;

    // Create a new chat with v0
    const chat = await v0.chats.create({
      message: prompt,
      system: systemMessage,
    });

    // Type guard to check if chat has the expected structure
    if (!('id' in chat) || !('messages' in chat)) {
      throw new Error('Unexpected response format from v0 API');
    }

    console.log(`[v0] Chat created: ${chat.id}`);

    // Extract the generated code from the latest message
    const latestMessage = chat.messages[chat.messages.length - 1];
    const code = latestMessage?.content || '';

    // Return the chat details
    return NextResponse.json({
      success: true,
      chatId: chat.id,
      webUrl: chat.webUrl,
      code,
      message: latestMessage,
    });
  } catch (error) {
    console.error('[v0] Error generating design:', error);
    
    return NextResponse.json(
      { 
        error: 'Failed to generate design', 
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}

