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

export async function POST(request: Request) {
  try {
    const { projectId, workspacePath } = await request.json();

    if (!projectId || !workspacePath) {
      return NextResponse.json(
        { error: 'projectId and workspacePath required' },
        { status: 400 }
      );
    }

    const adminDb = getAdminDb();

    // Update project with workspacePath
    await adminDb.collection('projects').doc(projectId).update({
      workspacePath,
      updatedAt: new Date(),
    });

    console.log(`[Fix Project] Set workspacePath for ${projectId}: ${workspacePath}`);

    // Now find and link all matching sessions
    const sessionsSnapshot = await adminDb
      .collection('sessions')
      .where('workspacePath', '==', workspacePath)
      .where('needsProjectAssociation', '==', true)
      .get();

    const batch = adminDb.batch();
    let linkedCount = 0;

    for (const sessionDoc of sessionsSnapshot.docs) {
      batch.update(sessionDoc.ref, {
        projectId,
        needsProjectAssociation: false,
        updatedAt: new Date(),
      });
      linkedCount++;
    }

    await batch.commit();

    console.log(`[Fix Project] Linked ${linkedCount} sessions to project ${projectId}`);

    return NextResponse.json({
      success: true,
      projectId,
      workspacePath,
      sessionsLinked: linkedCount,
    });
  } catch (error: any) {
    console.error('[Fix Project] Error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

