import { LeagueMembershipService } from '@/lib/services/leagues/LeagueMembershipService';
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';

export class LeagueMembershipUtility {
  /**
   * Derive a driver's primary league from cached memberships.
   * Prefers any active membership and returns the first matching league.
   */
  static getPrimaryLeagueIdForDriver(driverId: string): string | null {
    for (const [leagueId, members] of LeagueMembershipService.getCachedMembershipsIterator()) {
      if (members.some((m) => m.driverId === driverId && m.status === 'active')) {
        return leagueId;
      }
    }
    return null;
  }

  /**
   * Check if a driver is owner or admin of a league.
   */
  static isOwnerOrAdmin(leagueId: string, driverId: string): boolean {
    const membership = LeagueMembershipService.getMembership(leagueId, driverId);
    if (!membership) return false;
    return LeagueRoleUtility.isLeagueAdminOrHigherRole(membership.role);
  }
}
