/**
 * Migration Script: Add Phase Tracking to Existing Projects
 * 
 * Run with: npx tsx scripts/add-phase-tracking.ts
 */

import { getAdminDb } from '../lib/firebase/admin';

async function addPhaseTracking() {
  const adminDb = getAdminDb();
  
  console.log('🔍 Finding projects without phase tracking...\n');
  
  const projectsSnapshot = await adminDb.collection('projects').get();
  
  let updatedCount = 0;
  let skippedCount = 0;
  
  for (const doc of projectsSnapshot.docs) {
    const data = doc.data();
    
    // Skip if already has phase tracking
    if (data.currentPhase) {
      console.log(`⏭️  Skipping ${data.name} (${doc.id}) - already has phase tracking`);
      skippedCount++;
      continue;
    }
    
    // Add phase tracking
    await doc.ref.update({
      currentPhase: 'gathering',
      phaseStatus: 'not_started',
      phaseData: {},
      phaseHistory: [],
      updatedAt: new Date()
    });
    
    console.log(`✅ Updated ${data.name} (${doc.id}) - initialized with gathering phase`);
    updatedCount++;
  }
  
  console.log(`\n📊 Migration Complete:`);
  console.log(`   Updated: ${updatedCount} projects`);
  console.log(`   Skipped: ${skippedCount} projects`);
  console.log(`   Total: ${projectsSnapshot.size} projects\n`);
}

// Run migration
addPhaseTracking()
  .then(() => {
    console.log('✅ Migration successful!');
    process.exit(0);
  })
  .catch((error) => {
    console.error('❌ Migration failed:', error);
    process.exit(1);
  });

