/**
 * Check existing test users in the system
 */

import { createClient } from '@supabase/supabase-js';
import dotenv from 'dotenv';

// Load environment variables
dotenv.config();

const supabaseUrl = process.env.PUBLIC_SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;

if (!supabaseUrl || !supabaseServiceKey) {
  console.error('❌ Missing required environment variables');
  process.exit(1);
}

// Create Supabase admin client
const supabase = createClient(supabaseUrl, supabaseServiceKey, {
  auth: {
    autoRefreshToken: false,
    persistSession: false
  }
});

async function checkUsers() {
  console.log('🔍 Checking existing users in the system...\n');
  
  try {
    // List all auth users
    const { data: authUsers, error: authError } = await supabase.auth.admin.listUsers();
    
    if (authError) {
      console.error('❌ Error fetching auth users:', authError.message);
      return;
    }
    
    console.log(`📊 Found ${authUsers.users.length} auth users:`);
    
    for (const user of authUsers.users) {
      console.log(`  📧 ${user.email} - ID: ${user.id.substring(0, 8)}...`);
      
      // Check if user has database record
      const { data: dbUser, error: dbError } = await supabase
        .from('users')
        .select('role, organization_id')
        .eq('id', user.id)
        .single();
        
      if (dbUser) {
        console.log(`    📋 Role: ${dbUser.role} | Org: ${dbUser.organization_id}`);
      } else {
        console.log(`    ⚠️  No database record found`);
      }
    }
    
    console.log('\n🎯 Test User Status:');
    
    const adminUser = authUsers.users.find(u => u.email === 'admin@bct.com');
    const regularUser = authUsers.users.find(u => u.email === 'user@bct.com');
    const workingAdmin = authUsers.users.find(u => u.email === 'tmartinez@gmail.com');
    
    console.log(`  admin@bct.com: ${adminUser ? '✅ EXISTS' : '❌ MISSING'}`);
    console.log(`  user@bct.com: ${regularUser ? '✅ EXISTS' : '❌ MISSING'}`);
    console.log(`  tmartinez@gmail.com: ${workingAdmin ? '✅ EXISTS (WORKING)' : '❌ MISSING'}`);
    
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

checkUsers().catch(console.error);