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

/**
 * Migration script to set up permissions for existing clubs
 * This script:
 * 1. Sets default role='member' for all approved users without a role
 * 2. Identifies and marks the first user (by creation date) of each club as owner
 */

async function migratePermissions() {
  const report = [];
  report.push('Starting permissions migration...');

  try {
    // Get all clubs
    const clubs = await Club.findAll({
      include: [{
        model: UserClub,
        include: [{
          model: User,
          as: 'user'
        }],
        where: {
          approved: true
        },
        order: [['createdAt', 'ASC']]
      }]
    });

    report.push(`Found ${clubs.length} club(s)`);

    for (const club of clubs) {
      report.push(``);
      report.push(`--- Club: ${club.name} (ID: ${club.id}) ---`);
      
      const userClubs = await UserClub.findAll({
        where: {
          clubId: club.id,
          approved: true
        },
        include: [{
          model: User,
          as: 'user'
        }],
        order: [['createdAt', 'ASC']]
      });

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

      // First user becomes owner
      const firstUser = userClubs[0];
      
      report.push(`  Members found: ${userClubs.length}`);
      report.push(`  First member (will be owner): ${firstUser.user.email}`);

      for (let i = 0; i < userClubs.length; i++) {
        const userClub = userClubs[i];
        const isFirstUser = i === 0;
        
        // Set role if not set
        if (!userClub.role) {
          userClub.role = isFirstUser ? 'admin' : 'member';
        }
        
        // Set owner flag
        userClub.isOwner = isFirstUser;
        
        await userClub.save();
        
        report.push(`  ✓ Updated ${userClub.user.email}: role=${userClub.role}, isOwner=${userClub.isOwner}`);
      }
    }

    report.push('');
    report.push('✅ Migration completed successfully!');
    report.push('');
    report.push('Summary:');
    
    // Show summary
    const owners = await UserClub.findAll({
      where: {
        isOwner: true
      },
      include: [
        {
          model: User,
          as: 'user'
        },
        {
          model: Club,
          as: 'club'
        }
      ]
    });

    report.push(`\nClub Owners (${owners.length}):`);
    for (const owner of owners) {
      report.push(`  - ${owner.club.name}: ${owner.user.email}`);
    }

    const admins = await UserClub.count({
      where: { role: 'admin' }
    });
    const members = await UserClub.count({
      where: { role: 'member' }
    });

    report.push('');
    report.push('Role Distribution:');
    report.push(`  - Admins: ${admins}`);
    report.push(`  - Members: ${members}`);

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

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


