/**
 * Manual Extraction Trigger
 * 
 * Endpoint to manually run backend extraction for a project.
 * Useful for testing or re-running extraction.
 */

import { NextResponse } from 'next/server';
import { getAdminAuth } from '@/lib/firebase/admin';
import { runBackendExtractionForProject } from '@/lib/server/backend-extractor';

export const maxDuration = 300; // 5 minutes for extraction

export async function POST(
  request: Request,
  context: { params: Promise<{ projectId: string }> | { projectId: string } }
) {
  try {
    // Verify auth
    const authHeader = request.headers.get('Authorization');
    if (!authHeader?.startsWith('Bearer ')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const idToken = authHeader.split('Bearer ')[1];
    const adminAuth = getAdminAuth();
    
    try {
      await adminAuth.verifyIdToken(idToken);
    } catch (error) {
      return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
    }

    // Handle async params
    const params = 'then' in context.params ? await context.params : context.params;
    const projectId = params.projectId;

    if (!projectId) {
      return NextResponse.json({ error: 'Missing projectId' }, { status: 400 });
    }

    console.log(`[API] Manual extraction triggered for project ${projectId}`);

    // Run extraction
    await runBackendExtractionForProject(projectId);

    return NextResponse.json({
      success: true,
      message: 'Extraction completed successfully',
    });
  } catch (error) {
    console.error('[API] Extraction failed:', error);
    return NextResponse.json(
      {
        error: 'Extraction failed',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

