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

/**
 * GET - Get current phase for a project
 * POST - Update phase (start, complete, or add data)
 */

export async function GET(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();
    
    await adminAuth.verifyIdToken(idToken);

    const { searchParams } = new URL(request.url);
    const projectId = searchParams.get('projectId');

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

    // Get project phase data
    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 current phase info
    return NextResponse.json({
      currentPhase: projectData?.currentPhase || 'gathering',
      phaseStatus: projectData?.phaseStatus || 'not_started',
      phaseData: projectData?.phaseData || {},
      phaseHistory: projectData?.phaseHistory || []
    });
  } catch (error) {
    console.error('Error getting project phase:', error);
    return NextResponse.json(
      { error: 'Failed to get phase', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

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();
    
    const decodedToken = await adminAuth.verifyIdToken(idToken);
    const userId = decodedToken.uid;

    const body = await request.json();
    const { projectId, action, phase, data } = body;

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

    const projectRef = adminDb.collection('projects').doc(projectId);
    const projectDoc = await projectRef.get();

    if (!projectDoc.exists) {
      return NextResponse.json({ error: 'Project not found' }, { status: 404 });
    }

    const projectData = projectDoc.data();

    // Handle different actions
    switch (action) {
      case 'start': {
        // Start a new phase
        if (!phase) {
          return NextResponse.json({ error: 'phase required for start action' }, { status: 400 });
        }

        await projectRef.update({
          currentPhase: phase,
          phaseStatus: 'in_progress',
          [`phaseData.${phase}.startedAt`]: FieldValue.serverTimestamp(),
          updatedAt: FieldValue.serverTimestamp()
        });

        console.log(`[Phase] Started ${phase} for project ${projectId}`);
        return NextResponse.json({ success: true, phase, status: 'in_progress' });
      }

      case 'complete': {
        // Complete current phase
        const currentPhase = projectData?.currentPhase || 'gathering';
        
        await projectRef.update({
          phaseStatus: 'completed',
          [`phaseData.${currentPhase}.completedAt`]: FieldValue.serverTimestamp(),
          phaseHistory: FieldValue.arrayUnion({
            phase: currentPhase,
            completedAt: FieldValue.serverTimestamp()
          }),
          updatedAt: FieldValue.serverTimestamp()
        });

        console.log(`[Phase] Completed ${currentPhase} for project ${projectId}`);
        return NextResponse.json({ success: true, phase: currentPhase, status: 'completed' });
      }

      case 'save_data': {
        // Save phase-specific data (insights, vision board, etc.)
        const currentPhase = projectData?.currentPhase || 'gathering';
        
        await projectRef.update({
          [`phaseData.${currentPhase}.data`]: data,
          [`phaseData.${currentPhase}.lastUpdated`]: FieldValue.serverTimestamp(),
          updatedAt: FieldValue.serverTimestamp()
        });

        console.log(`[Phase] Saved data for ${currentPhase} in project ${projectId}`);
        return NextResponse.json({ success: true, phase: currentPhase });
      }

      case 'add_insight': {
        // Add a gathering insight
        if (!data || !data.insight) {
          return NextResponse.json({ error: 'insight data required' }, { status: 400 });
        }

        await projectRef.update({
          'phaseData.gathering.insights': FieldValue.arrayUnion(data),
          updatedAt: FieldValue.serverTimestamp()
        });

        console.log(`[Phase] Added insight to project ${projectId}`);
        return NextResponse.json({ success: true });
      }

      default:
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
    }
  } catch (error) {
    console.error('Error updating project phase:', error);
    return NextResponse.json(
      { error: 'Failed to update phase', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

