import { LeagueSettingsService } from '@/lib/services/leagues/LeagueSettingsService';
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 LeagueSettingsService.getCachedMembershipsIterator()) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      if (members.some((m: any) => 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 {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const membership = LeagueSettingsService.getMembership(leagueId, driverId) as any;
    if (!membership) return false;
    return LeagueRoleUtility.isLeagueAdminOrHigherRole(membership.role);
  }
}
