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

const prisma = new PrismaClient();

async function createMissingProfiles() {
  console.log('🔧 Creating missing profiles for users...\n');
  
  try {
    // Find users without profiles
    const usersWithoutProfiles = await prisma.user.findMany({
      where: {
        profile: null
      },
      select: {
        id: true,
        email: true,
        role: true,
        createdAt: true,
      }
    });

    if (usersWithoutProfiles.length === 0) {
      console.log('✅ All users already have profiles!');
      return;
    }

    console.log(`Found ${usersWithoutProfiles.length} users without profiles:`);
    usersWithoutProfiles.forEach((user, index) => {
      console.log(`${index + 1}. ${user.email} (${user.role})`);
    });

    console.log('\n🛠️  Creating profiles...');

    // Create profiles for users without them
    let created = 0;
    for (const user of usersWithoutProfiles) {
      try {
        // Extract name from email as fallback
        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) : '';

        const profile = await prisma.profile.create({
          data: {
            userId: user.id,
            firstName: firstName,
            lastName: lastName,
            countryId: 'LU', // Default to Luxembourg
          }
        });

        console.log(`✅ Created profile for ${user.email}: ${firstName} ${lastName}`);
        created++;
      } catch (error) {
        console.error(`❌ Failed to create profile for ${user.email}:`, error.message);
      }
    }

    console.log(`\n🎉 Successfully created ${created} profiles!`);

    if (created > 0) {
      console.log('\n📋 Summary of created profiles:');
      const newProfiles = await prisma.profile.findMany({
        where: {
          userId: {
            in: usersWithoutProfiles.map(u => u.id)
          }
        },
        include: {
          user: {
            select: {
              email: true,
              role: true,
            }
          }
        }
      });

      newProfiles.forEach((profile, index) => {
        console.log(`${index + 1}. ${profile.user.email}`);
        console.log(`   Name: ${profile.firstName} ${profile.lastName}`);
        console.log(`   Role: ${profile.user.role}`);
        console.log('   ---');
      });
    }

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

// Add 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');
  // For dry run, just show what would be created
  (async () => {
    const usersWithoutProfiles = await prisma.user.findMany({
      where: {
        profile: null
      },
      select: {
        id: true,
        email: true,
        role: true,
      }
    });

    if (usersWithoutProfiles.length === 0) {
      console.log('✅ All users already have profiles!');
    } else {
      console.log(`Would create profiles for ${usersWithoutProfiles.length} users:`);
      usersWithoutProfiles.forEach((user, index) => {
        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) : '';
        console.log(`${index + 1}. ${user.email} → ${firstName} ${lastName}`);
      });
      console.log('\nRun without --dry-run to create these profiles');
    }
    await prisma.$disconnect();
  })();
} else {
  createMissingProfiles();
}