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

/**
 * Save vision answers to Firestore
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const body = await request.json();
    const { visionAnswers } = body;

    if (!visionAnswers || !visionAnswers.q1 || !visionAnswers.q2 || !visionAnswers.q3) {
      return NextResponse.json(
        { error: 'All 3 vision answers are required' },
        { status: 400 }
      );
    }

    const adminDb = getAdminDb();

    // Save vision answers and mark ready for MVP
    await adminDb.collection('projects').doc(projectId).set(
      {
        visionAnswers: {
          q1: visionAnswers.q1,
          q2: visionAnswers.q2,
          q3: visionAnswers.q3,
          allAnswered: true,
          updatedAt: visionAnswers.updatedAt || new Date().toISOString(),
        },
        readyForMVP: true,
        currentPhase: 'mvp',
        phaseStatus: 'ready',
      },
      { merge: true }
    );

    console.log(`[Vision API] Saved vision answers for project ${projectId}`);

    // Trigger MVP generation (async - don't wait)
    console.log(`[Vision API] Triggering MVP generation for project ${projectId}...`);
    fetch(new URL(`/api/projects/${projectId}/mvp-checklist`, request.url).toString(), {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
    }).catch((error) => {
      console.error(`[Vision API] Failed to trigger MVP generation:`, error);
    });

    return NextResponse.json({
      success: true,
      message: 'Vision answers saved and MVP generation triggered',
    });
  } catch (error) {
    console.error('[Vision API] Error saving vision answers:', error);
    return NextResponse.json(
      {
        error: 'Failed to save vision answers',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

