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

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

    console.log('[v0] Attempting to list chats...');

    // Try to list chats - this may or may not be supported
    // The v0 SDK documentation shows chats.create() but we need to check if list() exists
    try {
      // @ts-ignore - Checking if this method exists
      const chats = await v0.chats.list();
      console.log('[v0] Chats retrieved:', chats);
      
      return NextResponse.json({
        success: true,
        chats,
        count: chats?.length || 0,
      });
    } catch (listError) {
      console.error('[v0] List method error:', listError);
      
      // Try alternative: Get account info or projects
      try {
        // @ts-ignore - Checking if this method exists
        const projects = await v0.projects?.list();
        console.log('[v0] Projects retrieved:', projects);
        
        return NextResponse.json({
          success: true,
          projects,
          count: projects?.length || 0,
          note: 'Retrieved projects instead of chats'
        });
      } catch (projectError) {
        console.error('[v0] Projects error:', projectError);
        
        return NextResponse.json({
          error: 'Unable to list chats or projects',
          details: 'The v0 SDK may not support listing existing chats via API',
          suggestion: 'You may need to manually provide chat IDs to import existing designs',
          sdkError: listError instanceof Error ? listError.message : 'Unknown error'
        }, { status: 400 });
      }
    }
  } catch (error) {
    console.error('[v0] Error:', error);
    
    return NextResponse.json(
      { 
        error: 'Failed to access v0 API', 
        details: error instanceof Error ? error.message : 'Unknown error',
        tip: 'The v0 SDK primarily supports creating new chats. To import existing designs, you may need to provide specific chat IDs or URLs.'
      },
      { status: 500 }
    );
  }
}

