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

export async function GET(
  request: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    
    // Authentication (skip in development if no auth header)
    const authHeader = request.headers.get('Authorization');
    const isDevelopment = process.env.NODE_ENV === 'development';
    
    if (!isDevelopment || authHeader?.startsWith('Bearer ')) {
      if (!authHeader?.startsWith('Bearer ')) {
        return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
      }

      const token = authHeader.substring(7);
      const auth = getAdminAuth();
      const decoded = await auth.verifyIdToken(token);
      
      if (!decoded?.uid) {
        return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
      }
    }

    // Fetch project from Firestore
    const adminDb = getAdminDb();
    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();

    return NextResponse.json({
      success: true,
      project: {
        id: projectDoc.id,
        ...projectData,
      },
    });
  } catch (error) {
    console.error('[API /projects/:id] Error fetching project:', error);
    return NextResponse.json(
      { 
        error: 'Failed to fetch project',
        details: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
}

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const body = await request.json();
    
    // Authentication (skip in development if no auth header)
    const authHeader = request.headers.get('Authorization');
    const isDevelopment = process.env.NODE_ENV === 'development';
    
    if (!isDevelopment || authHeader?.startsWith('Bearer ')) {
      if (!authHeader?.startsWith('Bearer ')) {
        return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
      }

      const token = authHeader.substring(7);
      const auth = getAdminAuth();
      const decoded = await auth.verifyIdToken(token);
      
      if (!decoded?.uid) {
        return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
      }
    }

    // Update project in Firestore
    const adminDb = getAdminDb();
    const updateData: any = {};

    // Only update fields that are provided
    if (body.vision !== undefined) updateData.vision = body.vision;
    if (body.description !== undefined) updateData.description = body.description;
    if (body.name !== undefined) updateData.name = body.name;
    if (body.githubRepo !== undefined) updateData.githubRepo = body.githubRepo;

    updateData.updatedAt = new Date().toISOString();

    await adminDb.collection('projects').doc(projectId).update(updateData);

    return NextResponse.json({
      success: true,
      message: 'Project updated successfully',
      updated: Object.keys(updateData)
    });

  } catch (error) {
    console.error('[API /projects/:id] Error updating project:', error);
    return NextResponse.json(
      { 
        error: 'Failed to update project',
        details: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
}

