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

const prisma = new PrismaClient();

async function fixSessionNames() {
  console.log('🔧 Fixing session name issues...\n');
  
  try {
    // Get all users with their profiles
    const allUsers = await prisma.user.findMany({
      include: {
        profile: true,
      },
    });

    console.log(`📊 Found ${allUsers.length} users in database\n`);

    let issuesFound = 0;
    let issuesFixed = 0;

    // Issue 1: Users without profiles
    const usersWithoutProfiles = allUsers.filter(user => !user.profile);
    if (usersWithoutProfiles.length > 0) {
      console.log(`❌ Issue 1: ${usersWithoutProfiles.length} users without profiles`);
      issuesFound++;
      
      console.log('   Creating profiles...');
      for (const user of usersWithoutProfiles) {
        try {
          const emailPrefix = user.email.split('@')[0];
          const nameParts = emailPrefix.split(/[._-]/);
          const firstName = nameParts[0] ? 
            nameParts[0].charAt(0).toUpperCase() + nameParts[0].slice(1) : 
            'User';
          const lastName = nameParts[1] ? 
            nameParts[1].charAt(0).toUpperCase() + nameParts[1].slice(1) : 
            '';

          await prisma.profile.create({
            data: {
              userId: user.id,
              firstName: firstName,
              lastName: lastName,
              countryId: 'LU',
            }
          });
          console.log(`   ✅ Created profile for ${user.email}: ${firstName} ${lastName}`);
        } catch (error) {
          console.log(`   ❌ Failed to create profile for ${user.email}: ${error.message}`);
        }
      }
      issuesFixed++;
    } else {
      console.log('✅ All users have profiles');
    }

    // Issue 2: Profiles without names
    const usersWithProfiles = allUsers.filter(user => user.profile);
    const profilesWithoutNames = usersWithProfiles.filter(user => {
      const profile = user.profile;
      return !profile.firstName && !profile.lastName;
    });

    if (profilesWithoutNames.length > 0) {
      console.log(`\n❌ Issue 2: ${profilesWithoutNames.length} profiles without names`);
      issuesFound++;
      
      console.log('   Adding names based on email...');
      for (const user of profilesWithoutNames) {
        try {
          const emailPrefix = user.email.split('@')[0];
          const nameParts = emailPrefix.split(/[._-]/);
          const firstName = nameParts[0] ? 
            nameParts[0].charAt(0).toUpperCase() + nameParts[0].slice(1) : 
            'User';
          const lastName = nameParts[1] ? 
            nameParts[1].charAt(0).toUpperCase() + nameParts[1].slice(1) : 
            '';

          await prisma.profile.update({
            where: { userId: user.id },
            data: {
              firstName: firstName,
              lastName: lastName,
            }
          });
          console.log(`   ✅ Updated profile for ${user.email}: ${firstName} ${lastName}`);
        } catch (error) {
          console.log(`   ❌ Failed to update profile for ${user.email}: ${error.message}`);
        }
      }
      issuesFixed++;
    } else {
      console.log('✅ All profiles have names');
    }

    // Issue 3: Profiles with only partial names
    const partialNames = usersWithProfiles.filter(user => {
      const profile = user.profile;
      return (profile.firstName && !profile.lastName) || (!profile.firstName && profile.lastName);
    });

    if (partialNames.length > 0) {
      console.log(`\n⚠️  Issue 3: ${partialNames.length} profiles with partial names`);
      issuesFound++;
      
      console.log('   Fixing partial names...');
      for (const user of partialNames) {
        try {
          const profile = user.profile;
          const emailPrefix = user.email.split('@')[0];
          const nameParts = emailPrefix.split(/[._-]/);
          
          const updates = {};
          if (!profile.firstName) {
            updates.firstName = nameParts[0] ? 
              nameParts[0].charAt(0).toUpperCase() + nameParts[0].slice(1) : 
              'User';
          }
          if (!profile.lastName && nameParts[1]) {
            updates.lastName = nameParts[1].charAt(0).toUpperCase() + nameParts[1].slice(1);
          }

          if (Object.keys(updates).length > 0) {
            await prisma.profile.update({
              where: { userId: user.id },
              data: updates
            });
            console.log(`   ✅ Updated ${user.email}: added ${Object.keys(updates).join(', ')}`);
          }
        } catch (error) {
          console.log(`   ❌ Failed to update profile for ${user.email}: ${error.message}`);
        }
      }
      issuesFixed++;
    } else {
      console.log('✅ All profiles have complete names');
    }

    console.log('\n' + '='.repeat(50));
    console.log('📋 SUMMARY');
    console.log('='.repeat(50));
    console.log(`Issues found: ${issuesFound}`);
    console.log(`Issues fixed: ${issuesFixed}`);

    if (issuesFixed > 0) {
      console.log('\n🎉 Session name issues have been fixed!');
      console.log('Users should now see proper names in their sessions.');
    } else {
      console.log('\n✅ No session name issues found!');
    }

    // Show final status
    console.log('\n📊 Final Status Check:');
    const finalUsers = await prisma.user.findMany({
      include: { profile: true },
    });

    const sessionNames = finalUsers.map(user => {
      let displayName = 'Unknown User';
      if (user.profile && (user.profile.firstName || user.profile.lastName)) {
        displayName = `${user.profile.firstName || ''} ${user.profile.lastName || ''}`.trim();
      } else if (user.email) {
        displayName = user.email.split('@')[0];
      }
      
      return {
        email: user.email,
        displayName,
        hasProfile: !!user.profile,
        hasName: !!(user.profile?.firstName || user.profile?.lastName),
      };
    });

    console.log(`Total users: ${sessionNames.length}`);
    console.log(`Users with profiles: ${sessionNames.filter(u => u.hasProfile).length}`);
    console.log(`Users with names: ${sessionNames.filter(u => u.hasName).length}`);
    
    const stillUsingEmail = sessionNames.filter(u => !u.hasName);
    if (stillUsingEmail.length > 0) {
      console.log(`\n⚠️  ${stillUsingEmail.length} users still using email as display name:`);
      stillUsingEmail.forEach(u => console.log(`   - ${u.email} → "${u.displayName}"`));
    }

  } catch (error) {
    console.error('❌ Error fixing session names:', error);
  } finally {
    await prisma.$disconnect();
  }
}

// Command line argument parsing
const args = process.argv.slice(2);
const dryRun = args.includes('--dry-run') || args.includes('-n');

if (dryRun) {
  console.log('🔍 DRY RUN MODE - No changes will be made\n');
  // Show what would be fixed without making changes
  (async () => {
    try {
      const allUsers = await prisma.user.findMany({
        include: { profile: true },
      });

      console.log(`📊 Found ${allUsers.length} users\n`);

      const usersWithoutProfiles = allUsers.filter(user => !user.profile);
      const usersWithProfiles = allUsers.filter(user => user.profile);
      const profilesWithoutNames = usersWithProfiles.filter(user => {
        const profile = user.profile;
        return !profile.firstName && !profile.lastName;
      });
      const partialNames = usersWithProfiles.filter(user => {
        const profile = user.profile;
        return (profile.firstName && !profile.lastName) || (!profile.firstName && profile.lastName);
      });

      console.log(`Would fix:`);
      console.log(`- ${usersWithoutProfiles.length} users without profiles`);
      console.log(`- ${profilesWithoutNames.length} profiles without names`);
      console.log(`- ${partialNames.length} profiles with partial names`);
      
      console.log('\nRun without --dry-run to apply these fixes');
    } catch (error) {
      console.error('Error:', error);
    } finally {
      await prisma.$disconnect();
    }
  })();
} else {
  fixSessionNames();
}