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

export async function POST(request: Request) {
  try {
    const { chatId, chatUrl } = await request.json();

    if (!chatId && !chatUrl) {
      return NextResponse.json(
        { error: 'Either chatId or chatUrl 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 }
      );
    }

    // Extract chat ID from URL if provided
    let extractedChatId = chatId;
    if (chatUrl && !chatId) {
      // v0.dev URLs look like: https://v0.dev/chat/abc123xyz
      const match = chatUrl.match(/\/chat\/([^/?]+)/);
      if (match) {
        extractedChatId = match[1];
      } else {
        return NextResponse.json(
          { error: 'Invalid v0 chat URL format' },
          { status: 400 }
        );
      }
    }

    console.log(`[v0] Attempting to import chat: ${extractedChatId}`);

    // The v0 SDK doesn't support retrieving individual chats by ID
    // We'll store a reference to the chat URL for the user to access it
    const fullChatUrl = chatUrl || `https://v0.dev/chat/${extractedChatId}`;
    
    console.log(`[v0] Importing chat reference: ${extractedChatId}`);

    const chatInfo = {
      id: extractedChatId,
      webUrl: fullChatUrl,
      message: 'Chat link saved. You can access it via the web URL.',
      note: 'The v0 API does not currently support retrieving chat history via API. Use the web URL to view and continue the conversation.'
    };

    return NextResponse.json({
      success: true,
      chat: chatInfo,
      message: 'Chat reference saved successfully'
    });
  } catch (error) {
    console.error('[v0] Error importing chat:', error);
    
    return NextResponse.json(
      { 
        error: 'Failed to import chat', 
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}

// Also support GET for testing
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const chatId = searchParams.get('chatId');
  const chatUrl = searchParams.get('chatUrl');

  if (!chatId && !chatUrl) {
    return NextResponse.json({
      message: 'Import a v0 chat',
      usage: 'POST /api/v0/import-chat with { "chatId": "abc123" } or { "chatUrl": "https://v0.dev/chat/abc123" }',
      example: {
        method: 'POST',
        body: {
          chatUrl: 'https://v0.dev/chat/your-chat-id'
        }
      }
    });
  }

  // Forward to POST handler
  const body = JSON.stringify({ chatId, chatUrl });
  const req = new Request(request.url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body,
  });

  return POST(req);
}

