import type { LeagueActivity } from '@/components/leagues/LeagueActivityFeed';
import { Result } from '@/lib/contracts/Result';
import { DomainError, Service } from '@/lib/contracts/services/Service';

export class LeagueActivityService implements Service {
  processLeagueActivities(raceList: any[], limit: number): Result<LeagueActivity[], DomainError> {
    const activities: LeagueActivity[] = [];
    
    const completedRaces = raceList
      .filter((r) => r.status === 'completed')
      .sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime())
      .slice(0, 5);

    const upcomingRaces = raceList
      .filter((r) => r.status === 'scheduled')
      .sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime())
      .slice(0, 3);

    for (const race of completedRaces) {
      activities.push({
        type: 'race_completed',
        raceId: race.id,
        raceName: `${race.track} - ${race.car}`,
        timestamp: new Date(race.scheduledAt),
      });
    }

    for (const race of upcomingRaces) {
      activities.push({
        type: 'race_scheduled',
        raceId: race.id,
        raceName: `${race.track} - ${race.car}`,
        timestamp: new Date(new Date(race.scheduledAt).getTime() - 7 * 24 * 60 * 60 * 1000), // Simulate schedule announcement
      });
    }

    // Sort all activities by timestamp
    activities.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
    if (activities.length > limit) {
      activities.splice(limit);
    }

    return Result.ok(activities);
  }
}
