import User from '../models/User.js';
import Club from '../models/Club.js';
import UserClub from '../models/UserClub.js';
import sequelize from '../database.js';

/**
 * Create test users with different roles
 */

const TEST_USERS = [
  {
    email: 'admin@test.de',
    password: 'test123',
    role: 'admin',
    isOwner: false
  },
  {
    email: 'trainer@test.de',
    password: 'test123',
    role: 'trainer',
    isOwner: false
  },
  {
    email: 'teammanager@test.de',
    password: 'test123',
    role: 'team_manager',
    isOwner: false
  },
  {
    email: 'tournamentmanager@test.de',
    password: 'test123',
    role: 'tournament_manager',
    isOwner: false
  },
  {
    email: 'member1@test.de',
    password: 'test123',
    role: 'member',
    isOwner: false
  },
  {
    email: 'member2@test.de',
    password: 'test123',
    role: 'member',
    isOwner: false
  }
];

async function createTestUsers() {
  const report = [];
  report.push('Creating test users...');

  try {
    // Get first club (or specify club ID)
    const clubs = await Club.findAll({ limit: 1 });
    
    if (clubs.length === 0) {
      console.error('❌ No clubs found! Please create a club first.');
      process.exit(1);
    }

    const club = clubs[0];
    report.push(`Using club: ${club.name} (ID: ${club.id})`);

    for (const userData of TEST_USERS) {
      report.push(`Creating user: ${userData.email} (${userData.role})...`);
      
      // Check if user already exists
      let user = await User.findOne({ where: { email: userData.email } });
      
      if (user) {
        report.push('  ⚠️  User already exists, using existing user');
      } else {
        // Create user
        user = await User.create({
          email: userData.email,
          password: userData.password,
          isActive: true
        });
        report.push('  ✓ User created');
      }

      // Check if user is already in club
      let userClub = await UserClub.findOne({
        where: {
          userId: user.id,
          clubId: club.id
        }
      });

      if (userClub) {
        report.push('  ⚠️  User already in club, updating role...');
        await userClub.update({
          role: userData.role,
          isOwner: userData.isOwner,
          approved: true
        });
        report.push(`  ✓ Updated to role: ${userData.role}`);
      } else {
        // Add user to club
        userClub = await UserClub.create({
          userId: user.id,
          clubId: club.id,
          role: userData.role,
          isOwner: userData.isOwner,
          approved: true
        });
        report.push(`  ✓ Added to club with role: ${userData.role}`);
      }
    }

    report.push('');
    report.push('✅ Test users created successfully!');
    
    // Show summary
    report.push('Summary:');
    report.push('========================================');
    report.push(`Club: ${club.name}`);
    report.push('');
    report.push('Test Users:');
    
    for (const userData of TEST_USERS) {
      report.push(`  ${userData.email.padEnd(25)} | ${userData.role.padEnd(15)} | Password: test123`);
    }
    
    report.push('');
    report.push('========================================');
    report.push('You can now login with any of these users!');
    report.push('All passwords are: test123');

  } catch (error) {
    console.error('❌ Error creating test users:', error);
    throw error;
  } finally {
    await sequelize.close();
    if (report.length > 0) {
      process.stdout.write(`${report.join('\n')}\n`);
    }
  }
}

// Run
createTestUsers().catch(err => {
  console.error('Fatal error:', err);
  process.exit(1);
});


