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

/**
 * Quick fix: Set first user of each club as owner/admin
 * This is a simplified version for immediate use
 */

async function quickFixOwners() {
  const report = [];
  report.push('Quick Fix: Setting club owners...');

  try {
    const clubs = await Club.findAll();
    report.push(`Found ${clubs.length} club(s)`);

    for (const club of clubs) {
      report.push(`Club: ${club.name} (ID: ${club.id})`);
      
      // Find all approved members, ordered by creation date
      const userClubs = await UserClub.findAll({
        where: {
          clubId: club.id,
          approved: true
        },
        include: [{
          model: User,
          as: 'user',
          attributes: ['id', 'email']
        }],
        order: [['createdAt', 'ASC']]
      });

      if (userClubs.length === 0) {
        report.push('  ⚠️  No approved members');
        continue;
      }

      // First user becomes owner
      const firstUserClub = userClubs[0];
      
      // Reset all users first (remove owner flag)
      await UserClub.update(
        { isOwner: false },
        { 
          where: { 
            clubId: club.id,
            approved: true 
          } 
        }
      );
      
      // Set first user as owner and admin
      await firstUserClub.update({
        isOwner: true,
        role: 'admin'
      });
      
      report.push(`  ✅ Owner: ${firstUserClub.user.email}`);
      
      // Set role for other members if not set
      for (let i = 1; i < userClubs.length; i++) {
        const uc = userClubs[i];
        if (!uc.role) {
          await uc.update({ role: 'member' });
          report.push(`  👤 Member: ${uc.user.email}`);
        }
      }
      report.push('');
    }

    report.push('✅ Quick fix completed!');
    
    // Show all owners
    const owners = await UserClub.findAll({
      where: { isOwner: true },
      include: [
        { model: User, as: 'user', attributes: ['email'] },
        { model: Club, as: 'club', attributes: ['name'] }
      ]
    });
    report.push('Current Club Owners:');
    for (const owner of owners) {
      report.push(`  📍 ${owner.club.name}: ${owner.user.email} (role: ${owner.role})`);
    }

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

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

