import { NextRequest, NextResponse } from 'next/server';
import admin from '@/lib/firebase/admin';

/**
 * Extract vision answers from chat history and save to project
 * This is a helper endpoint to migrate from AI chat-based vision collection
 * to the structured visionAnswers field
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const db = admin.firestore();

    console.log(`[Extract Vision] Extracting vision answers from chat for project ${projectId}`);

    // Get chat messages
    const conversationRef = db
      .collection('projects')
      .doc(projectId)
      .collection('conversations')
      .doc('ai_chat');

    const messagesSnapshot = await conversationRef
      .collection('messages')
      .orderBy('createdAt', 'asc')
      .get();

    if (messagesSnapshot.empty) {
      return NextResponse.json(
        { error: 'No chat messages found' },
        { status: 404 }
      );
    }

    const messages = messagesSnapshot.docs.map(doc => ({
      id: doc.id,
      ...doc.data()
    }));

    console.log(`[Extract Vision] Found ${messages.length} total messages`);

    // Extract user messages (answers to the 3 vision questions)
    const userMessages = messages.filter((m: any) => m.role === 'user');

    console.log(`[Extract Vision] Found ${userMessages.length} user messages`);

    if (userMessages.length < 3) {
      return NextResponse.json(
        { 
          error: 'Not enough answers found',
          details: `Found ${userMessages.length} answers, need 3`,
          userMessages: userMessages.map((m: any) => m.content?.substring(0, 100))
        },
        { status: 400 }
      );
    }

    // The first 3 user messages should be the answers to Q1, Q2, Q3
    const visionAnswers = {
      q1: userMessages[0].content,
      q2: userMessages[1].content,
      q3: userMessages[2].content,
      allAnswered: true,
      updatedAt: new Date().toISOString(),
    };

    console.log(`[Extract Vision] Extracted vision answers:`, {
      q1: visionAnswers.q1.substring(0, 50) + '...',
      q2: visionAnswers.q2.substring(0, 50) + '...',
      q3: visionAnswers.q3.substring(0, 50) + '...',
    });

    // Save to project
    await db.collection('projects').doc(projectId).set(
      {
        visionAnswers,
        readyForMVP: true,
        currentPhase: 'mvp',
        phaseStatus: 'ready',
      },
      { merge: true }
    );

    console.log(`[Extract Vision] ✅ Vision answers saved for project ${projectId}`);

    return NextResponse.json({
      success: true,
      message: 'Vision answers extracted and saved',
      visionAnswers: {
        q1: visionAnswers.q1.substring(0, 100) + '...',
        q2: visionAnswers.q2.substring(0, 100) + '...',
        q3: visionAnswers.q3.substring(0, 100) + '...',
      }
    });

  } catch (error) {
    console.error('[Extract Vision] Error:', error);
    return NextResponse.json(
      {
        error: 'Failed to extract vision answers',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

