import { NextRequest, NextResponse } from 'next/server';
import { authSession } from "@/lib/auth/session-server";
import { query } from '@/lib/db-postgres';

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const session = await authSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    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 rows = await query<{ id: string; data: any }>(
      `SELECT p.id, p.data FROM fs_projects p
       JOIN fs_users u ON u.id = p.user_id
       WHERE p.id = $1 AND u.data->>'email' = $2 LIMIT 1`,
      [projectId, session.user.email]
    );

    if (rows.length === 0) {
      return NextResponse.json({ error: 'Project not found' }, { status: 404 });
    }

    const current = rows[0].data ?? {};
    const updated = {
      ...current,
      visionAnswers: {
        q1: visionAnswers.q1,
        q2: visionAnswers.q2,
        q3: visionAnswers.q3,
        allAnswered: true,
        updatedAt: visionAnswers.updatedAt || new Date().toISOString(),
      },
      readyForMVP: true,
      currentPhase: 'mvp',
      phaseStatus: 'ready',
      updatedAt: new Date().toISOString(),
    };

    await query(
      `UPDATE fs_projects SET data = $1::jsonb WHERE id = $2`,
      [JSON.stringify(updated), projectId]
    );

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

    // Trigger MVP generation (async - don't wait)
    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 }
    );
  }
}
