const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

async function checkUsersAndProfiles() {
  console.log('🔍 Checking database for users and profiles...\n');
  
  try {
    // Get all users with their profile information
    const allUsers = await prisma.user.findMany({
      include: {
        profile: {
          include: {
            country: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    console.log(`📊 Database Statistics:`);
    console.log(`Total users: ${allUsers.length}`);
    
    if (allUsers.length === 0) {
      console.log('❌ No users found in the database');
      return;
    }

    // Separate users with and without profiles
    const usersWithProfiles = allUsers.filter(user => user.profile !== null);
    const usersWithoutProfiles = allUsers.filter(user => user.profile === null);

    console.log(`Users with profiles: ${usersWithProfiles.length}`);
    console.log(`Users without profiles: ${usersWithoutProfiles.length}`);
    
    if (usersWithoutProfiles.length > 0) {
      const percentage = ((usersWithoutProfiles.length / allUsers.length) * 100).toFixed(2);
      console.log(`⚠️  ${percentage}% of users don't have profiles\n`);
    } else {
      console.log(`✅ All users have profiles\n`);
    }

    // Show users without profiles
    if (usersWithoutProfiles.length > 0) {
      console.log('👥 Users WITHOUT profiles:');
      console.log('================================');
      usersWithoutProfiles.forEach((user, index) => {
        console.log(`${index + 1}. ID: ${user.id}`);
        console.log(`   Email: ${user.email}`);
        console.log(`   Role: ${user.role}`);
        console.log(`   Provider: ${user.provider || 'email'}`);
        console.log(`   Created: ${user.createdAt.toISOString()}`);
        console.log(`   Email Verified: ${user.emailVerified ? 'Yes' : 'No'}`);
        console.log('   ---');
      });
      console.log('');
    }

    // Show sample users with profiles
    if (usersWithProfiles.length > 0) {
      console.log('👤 Sample users WITH profiles:');
      console.log('===============================');
      const sampleSize = Math.min(3, usersWithProfiles.length);
      usersWithProfiles.slice(0, sampleSize).forEach((user, index) => {
        const profile = user.profile;
        const fullName = `${profile.firstName || ''} ${profile.lastName || ''}`.trim();
        
        console.log(`${index + 1}. ID: ${user.id}`);
        console.log(`   Email: ${user.email}`);
        console.log(`   Name: ${fullName || 'Not set'}`);
        console.log(`   Role: ${user.role}`);
        console.log(`   Phone: ${profile.phone || 'Not set'}`);
        console.log(`   City: ${profile.city || 'Not set'}`);
        console.log(`   Country: ${profile.country?.name || 'Not set'}`);
        console.log(`   Bio: ${profile.bio ? profile.bio.substring(0, 50) + '...' : 'Not set'}`);
        console.log(`   Profile Created: ${profile.createdAt.toISOString()}`);
        console.log('   ---');
      });
      console.log('');
    }

    // Check for incomplete profiles
    const incompleteProfiles = usersWithProfiles.filter(user => {
      const profile = user.profile;
      return !profile.firstName || !profile.lastName;
    });

    if (incompleteProfiles.length > 0) {
      console.log('⚠️  Users with incomplete profiles (missing names):');
      console.log('===================================================');
      incompleteProfiles.forEach((user, index) => {
        const profile = user.profile;
        console.log(`${index + 1}. Email: ${user.email}`);
        console.log(`   First Name: ${profile.firstName || 'MISSING'}`);
        console.log(`   Last Name: ${profile.lastName || 'MISSING'}`);
        console.log('   ---');
      });
      console.log('');
    }

    // Session name analysis
    console.log('🏷️  Session Display Name Analysis:');
    console.log('===================================');
    const nameAnalysis = allUsers.map(user => {
      let displayName = 'Unknown User';
      let nameSource = 'none';
      
      if (user.profile && (user.profile.firstName || user.profile.lastName)) {
        displayName = `${user.profile.firstName || ''} ${user.profile.lastName || ''}`.trim();
        nameSource = 'profile';
      } else if (user.email) {
        displayName = user.email.split('@')[0];
        nameSource = 'email';
      }
      
      return {
        email: user.email,
        displayName,
        nameSource,
        hasProfile: !!user.profile,
      };
    });

    const emailBasedNames = nameAnalysis.filter(u => u.nameSource === 'email');
    const profileBasedNames = nameAnalysis.filter(u => u.nameSource === 'profile');

    console.log(`Users using profile names: ${profileBasedNames.length}`);
    console.log(`Users using email-based names: ${emailBasedNames.length}`);

    if (emailBasedNames.length > 0) {
      console.log('\nUsers currently using email as display name:');
      emailBasedNames.slice(0, 5).forEach(user => {
        console.log(`  - ${user.email} → "${user.displayName}"`);
      });
    }

    // Recommendations
    console.log('\n💡 Recommendations:');
    console.log('===================');
    
    if (usersWithoutProfiles.length > 0) {
      console.log('1. Create profiles for users without them to ensure proper display names');
      console.log('   You can use the profile API PUT endpoint to create profiles');
    }
    
    if (incompleteProfiles.length > 0) {
      console.log('2. Encourage users to complete their profile information');
      console.log('   This will improve session display names');
    }
    
    if (emailBasedNames.length > 0) {
      console.log('3. Users without profile names will show email prefixes in sessions');
      console.log('   Consider prompting them to set up their names');
    }

    if (usersWithoutProfiles.length === 0 && incompleteProfiles.length === 0) {
      console.log('✅ All users have complete profiles with names!');
    }

  } catch (error) {
    console.error('❌ Error checking database:', error);
  } finally {
    await prisma.$disconnect();
  }
}

// Run the check
checkUsersAndProfiles();