import { NextResponse } from 'next/server';
import { adminDb } from '@/lib/firebase/admin';
import { FieldValue } from 'firebase-admin/firestore';

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

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

    // Verify the project belongs to the user
    const projectDoc = await adminDb.collection('projects').doc(projectId).get();
    
    if (!projectDoc.exists || projectDoc.data()?.userId !== userId) {
      return NextResponse.json(
        { error: 'Project not found or unauthorized' },
        { status: 403 }
      );
    }

    // Update all sessions with this workspace path to associate with the project
    const sessionsSnapshot = await adminDb
      .collection('sessions')
      .where('userId', '==', userId)
      .where('workspacePath', '==', workspacePath)
      .where('needsProjectAssociation', '==', true)
      .get();

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

    sessionsSnapshot.docs.forEach((doc: FirebaseFirestore.QueryDocumentSnapshot) => {
      batch.update(doc.ref, {
        projectId,
        needsProjectAssociation: false,
        updatedAt: FieldValue.serverTimestamp(),
      });
      count++;
    });

    await batch.commit();

    // Update the project's workspace path if not set
    if (!projectDoc.data()?.workspacePath) {
      await projectDoc.ref.update({
        workspacePath,
        updatedAt: FieldValue.serverTimestamp(),
      });
    }

    return NextResponse.json({
      success: true,
      sessionsUpdated: count,
      message: `Associated ${count} sessions with project`,
    });
  } catch (error) {
    console.error('Error associating sessions:', error);
    return NextResponse.json(
      {
        error: 'Failed to associate sessions',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

