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

export async function GET(
  request: Request,
  context: { params: Promise<{ projectId: string }> | { projectId: string } }
) {
  try {
    // 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 });
    }

    const adminDb = getAdminDb();

    // Fetch project to get extraction handoff
    const projectDoc = await adminDb.collection('projects').doc(projectId).get();
    
    if (!projectDoc.exists) {
      return NextResponse.json({ error: 'Project not found' }, { status: 404 });
    }

    const projectData = projectDoc.data();
    const extractionHandoff = projectData?.phaseData?.phaseHandoffs?.extraction;

    if (!extractionHandoff) {
      return NextResponse.json({ error: 'No extraction results found' }, { status: 404 });
    }

    return NextResponse.json({
      handoff: extractionHandoff,
    });
  } catch (error) {
    console.error('[extraction-handoff] Error:', error);
    return NextResponse.json(
      {
        error: 'Failed to fetch extraction handoff',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

export async function PATCH(
  request: Request,
  context: { params: Promise<{ projectId: string }> | { projectId: string } }
) {
  try {
    // 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 });
    }

    const body = await request.json();
    const { confirmed } = body;

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

    const adminDb = getAdminDb();

    // Fetch current handoff
    const projectDoc = await adminDb.collection('projects').doc(projectId).get();
    
    if (!projectDoc.exists) {
      return NextResponse.json({ error: 'Project not found' }, { status: 404 });
    }

    const projectData = projectDoc.data();
    const currentHandoff = projectData?.phaseData?.phaseHandoffs?.extraction;

    if (!currentHandoff) {
      return NextResponse.json({ error: 'No extraction handoff found' }, { status: 404 });
    }

    // Update the handoff with edited data
    const updatedHandoff = {
      ...currentHandoff,
      confirmed: {
        ...currentHandoff.confirmed,
        ...confirmed,
      },
      updatedAt: new Date().toISOString(),
    };

    // Save to Firestore
    await adminDb.collection('projects').doc(projectId).update({
      'phaseData.phaseHandoffs.extraction': updatedHandoff,
      updatedAt: new Date().toISOString(),
    });

    return NextResponse.json({
      success: true,
      handoff: updatedHandoff,
    });
  } catch (error) {
    console.error('[extraction-handoff] PATCH error:', error);
    return NextResponse.json(
      {
        error: 'Failed to update extraction handoff',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

