/**
 * Migration Script: Add Phase Tracking to Existing Projects
 * 
 * Run with: node scripts/add-phase-tracking.js
 */

const admin = require('firebase-admin');
const fs = require('fs');
const path = require('path');

// Load environment variables
require('dotenv').config({ path: '.env.local' });

// Initialize Firebase Admin
const serviceAccount = {
  projectId: process.env.FIREBASE_PROJECT_ID,
  clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
  privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n')
};

if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
  });
}

const db = admin.firestore();

async function addPhaseTracking() {
  console.log('🔍 Finding projects without phase tracking...\n');
  
  const projectsSnapshot = await db.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: admin.firestore.FieldValue.serverTimestamp()
    });
    
    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);
  });

