// MUST load environment variables BEFORE any other imports
require('dotenv').config({ path: require('path').resolve(__dirname, '../.env.local') });

import admin from 'firebase-admin';
import { FieldValue } from 'firebase-admin/firestore';

// Initialize Firebase Admin directly
if (!admin.apps.length) {
  const privateKey = process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n');
  
  if (!process.env.FIREBASE_PROJECT_ID || !process.env.FIREBASE_CLIENT_EMAIL || !privateKey) {
    throw new Error('Missing Firebase Admin credentials. Check your .env.local file.');
  }
  
  admin.initializeApp({
    credential: admin.credential.cert({
      projectId: process.env.FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: privateKey,
    }),
  });
  
  console.log('✅ Firebase Admin initialized successfully');
}

const adminDb = admin.firestore();
const adminAuth = admin.auth();

async function reassignMigratedData() {
  console.log('🚀 Starting data reassignment...\n');
  
  try {
    // Get the current user (mark@getacquired.com)
    console.log('📋 Finding current user: mark@getacquired.com');
    const currentUser = await adminAuth.getUserByEmail('mark@getacquired.com');
    console.log(`✅ Current user found: ${currentUser.uid}\n`);
    
    // Get the migrated user (mark@example.com)
    console.log('📋 Finding migrated user: mark@example.com');
    let migratedUser;
    try {
      migratedUser = await adminAuth.getUserByEmail('mark@example.com');
      console.log(`✅ Migrated user found: ${migratedUser.uid}\n`);
    } catch (error) {
      console.log('⚠️  Migrated user not found, will look for any migrated data by flag\n');
    }
    
    // Reassign all collections
    const collections = ['sessions', 'projects', 'clients', 'workCompleted'];
    
    for (const collectionName of collections) {
      console.log(`\n📋 Processing ${collectionName}...`);
      
      // Query for migrated documents
      let query = adminDb.collection(collectionName).where('migratedFrom', '==', 'postgresql');
      
      const snapshot = await query.get();
      
      if (snapshot.empty) {
        console.log(`  ℹ️  No migrated ${collectionName} found`);
        continue;
      }
      
      console.log(`  Found ${snapshot.size} migrated ${collectionName}`);
      
      // Update each document
      const batch = adminDb.batch();
      let count = 0;
      
      for (const doc of snapshot.docs) {
        const data = doc.data();
        const updates: any = {
          updatedAt: FieldValue.serverTimestamp(),
        };
        
        // Update userId field
        if (data.userId) {
          updates.userId = currentUser.uid;
        }
        
        // Update ownerId field (for clients)
        if (data.ownerId) {
          updates.ownerId = currentUser.uid;
        }
        
        batch.update(doc.ref, updates);
        count++;
        
        // Commit batch every 500 documents (Firestore limit)
        if (count % 500 === 0) {
          await batch.commit();
          console.log(`  ✅ Committed ${count} updates...`);
        }
      }
      
      // Commit remaining
      if (count % 500 !== 0) {
        await batch.commit();
      }
      
      console.log(`  ✅ Reassigned ${count} ${collectionName} to ${currentUser.email}`);
    }
    
    // Delete the temporary migrated user if it exists
    if (migratedUser) {
      console.log('\n📋 Cleaning up temporary migrated user account...');
      
      // Delete the user document
      await adminDb.collection('users').doc(migratedUser.uid).delete();
      
      // Delete the Auth account
      await adminAuth.deleteUser(migratedUser.uid);
      
      console.log('✅ Temporary user account deleted');
    }
    
    console.log('\n✅ Data reassignment completed successfully!');
    console.log(`\n🎉 All migrated data is now assigned to: ${currentUser.email}`);
    
  } catch (error) {
    console.error('\n❌ Data reassignment failed:', error);
    throw error;
  }
}

// Run reassignment
reassignMigratedData()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

