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

/**
 * Delete a project (soft delete - keeps sessions intact)
 * Sessions will remain in the database but projectId will be set to null
 */
export async function POST(request: Request) {
  try {
    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();
    const adminDb = getAdminDb();

    let userId: string;
    try {
      const decodedToken = await adminAuth.verifyIdToken(idToken);
      userId = decodedToken.uid;
    } catch (error) {
      return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
    }

    const { projectId } = await request.json();

    if (!projectId) {
      return NextResponse.json(
        { error: 'Project ID is required' },
        { status: 400 }
      );
    }

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

    if (projectDoc.data()?.userId !== userId) {
      return NextResponse.json(
        { error: 'Unauthorized to delete this project' },
        { status: 403 }
      );
    }

    // Delete the project document
    await adminDb.collection('projects').doc(projectId).delete();

    // Optional: Update sessions to remove project reference
    // This makes sessions "orphaned" but keeps all the data
    const sessionsSnapshot = await adminDb
      .collection('sessions')
      .where('projectId', '==', projectId)
      .get();

    if (!sessionsSnapshot.empty) {
      const batch = adminDb.batch();
      sessionsSnapshot.docs.forEach((doc) => {
        batch.update(doc.ref, {
          projectId: null,
          // Flag these as needing reassignment if user wants to link them later
          needsProjectAssociation: true,
          updatedAt: FieldValue.serverTimestamp(),
        });
      });
      await batch.commit();
    }

    return NextResponse.json({
      success: true,
      message: 'Project deleted successfully',
      sessionsPreserved: sessionsSnapshot.size,
    });
  } catch (error) {
    console.error('[Project Delete] Error:', error);
    return NextResponse.json(
      {
        error: 'Failed to delete project',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

