/**
 * Quick script to verify session associations in Firestore
 */

import { config } from 'dotenv';
import { resolve } from 'path';

// Load environment variables from .env.local
config({ path: resolve(__dirname, '../.env.local') });

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

async function checkSessionLinks() {
  const db = getAdminDb();

  console.log('🔍 Checking session associations...\n');

  // Get all sessions
  const sessionsSnapshot = await db.collection('sessions').get();
  
  console.log(`📊 Total sessions: ${sessionsSnapshot.size}\n`);

  // Group by status
  const linked: any[] = [];
  const unlinked: any[] = [];

  sessionsSnapshot.docs.forEach(doc => {
    const data = doc.data();
    const sessionInfo = {
      id: doc.id,
      workspaceName: data.workspaceName || 'Unknown',
      workspacePath: data.workspacePath,
      projectId: data.projectId,
      needsProjectAssociation: data.needsProjectAssociation,
      createdAt: data.createdAt?.toDate?.() || data.createdAt,
    };

    if (data.projectId) {
      linked.push(sessionInfo);
    } else {
      unlinked.push(sessionInfo);
    }
  });

  console.log(`✅ Linked to projects: ${linked.length}`);
  console.log(`⚠️  Not linked: ${unlinked.length}\n`);

  if (linked.length > 0) {
    console.log('📌 Linked Sessions:');
    linked.forEach(s => {
      console.log(`  - ${s.workspaceName} → Project: ${s.projectId?.substring(0, 8)}...`);
      console.log(`    needsProjectAssociation: ${s.needsProjectAssociation}`);
    });
    console.log('');
  }

  if (unlinked.length > 0) {
    console.log('⚠️  Unlinked Sessions:');
    unlinked.forEach(s => {
      console.log(`  - ${s.workspaceName}`);
      console.log(`    Path: ${s.workspacePath}`);
      console.log(`    needsProjectAssociation: ${s.needsProjectAssociation}`);
    });
    console.log('');
  }

  // Check projects
  const projectsSnapshot = await db.collection('projects').get();
  console.log(`📁 Total projects: ${projectsSnapshot.size}\n`);

  projectsSnapshot.docs.forEach(doc => {
    const data = doc.data();
    console.log(`  - ${data.productName || data.name || 'Unnamed'}`);
    console.log(`    ID: ${doc.id}`);
    console.log(`    Workspace: ${data.workspacePath || 'Not set'}`);
    console.log('');
  });

  process.exit(0);
}

checkSessionLinks().catch(error => {
  console.error('Error:', error);
  process.exit(1);
});

