| | | 1 | | using EHonda.KicktippAi.Core; |
| | | 2 | | using FirebaseAdapter.Models; |
| | | 3 | | using Google.Cloud.Firestore; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using NodaTime; |
| | | 6 | | |
| | | 7 | | namespace FirebaseAdapter; |
| | | 8 | | |
| | | 9 | | public class FirebaseMatchOutcomeRepository : IMatchOutcomeRepository |
| | | 10 | | { |
| | | 11 | | private const int ExpectedMatchesPerMatchday = 9; |
| | | 12 | | |
| | | 13 | | private readonly FirestoreDb _firestoreDb; |
| | | 14 | | private readonly ILogger<FirebaseMatchOutcomeRepository> _logger; |
| | | 15 | | private readonly string _matchOutcomesCollection; |
| | | 16 | | private readonly string _competition; |
| | | 17 | | |
| | 1 | 18 | | public FirebaseMatchOutcomeRepository( |
| | 1 | 19 | | FirestoreDb firestoreDb, |
| | 1 | 20 | | ILogger<FirebaseMatchOutcomeRepository> logger, |
| | 1 | 21 | | string? competition = null) |
| | | 22 | | { |
| | 1 | 23 | | _firestoreDb = firestoreDb ?? throw new ArgumentNullException(nameof(firestoreDb)); |
| | 1 | 24 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | 1 | 25 | | _matchOutcomesCollection = "match-outcomes"; |
| | 1 | 26 | | _competition = string.IsNullOrWhiteSpace(competition) |
| | 1 | 27 | | ? CompetitionIds.Bundesliga2025_26 |
| | 1 | 28 | | : competition.Trim(); |
| | 1 | 29 | | } |
| | | 30 | | |
| | | 31 | | public async Task<MatchOutcomeUpsertResult> UpsertMatchOutcomeAsync( |
| | | 32 | | CollectedMatchOutcome outcome, |
| | | 33 | | string communityContext, |
| | | 34 | | CancellationToken cancellationToken = default) |
| | | 35 | | { |
| | 1 | 36 | | var documentId = BuildDocumentId(outcome, communityContext); |
| | 1 | 37 | | var docRef = _firestoreDb.Collection(_matchOutcomesCollection).Document(documentId); |
| | 1 | 38 | | var snapshot = await docRef.GetSnapshotAsync(cancellationToken); |
| | 1 | 39 | | var now = Timestamp.GetCurrentTimestamp(); |
| | | 40 | | |
| | 1 | 41 | | if (!snapshot.Exists) |
| | | 42 | | { |
| | 1 | 43 | | var firestoreOutcome = ToFirestoreMatchOutcome(outcome, communityContext, documentId, now, now); |
| | 1 | 44 | | await docRef.SetAsync(firestoreOutcome, cancellationToken: cancellationToken); |
| | | 45 | | |
| | 1 | 46 | | return new MatchOutcomeUpsertResult( |
| | 1 | 47 | | MatchOutcomeWriteDisposition.Created, |
| | 1 | 48 | | ConvertToPersistedMatchOutcome(firestoreOutcome)); |
| | | 49 | | } |
| | | 50 | | |
| | 1 | 51 | | var existing = snapshot.ConvertTo<FirestoreMatchOutcome>(); |
| | 1 | 52 | | if (!NeedsUpdate(existing, outcome)) |
| | | 53 | | { |
| | 1 | 54 | | return new MatchOutcomeUpsertResult( |
| | 1 | 55 | | MatchOutcomeWriteDisposition.Unchanged, |
| | 1 | 56 | | ConvertToPersistedMatchOutcome(existing)); |
| | | 57 | | } |
| | | 58 | | |
| | 1 | 59 | | var updated = ToFirestoreMatchOutcome(outcome, communityContext, documentId, existing.CreatedAt, now); |
| | 1 | 60 | | await docRef.SetAsync(updated, cancellationToken: cancellationToken); |
| | | 61 | | |
| | 1 | 62 | | return new MatchOutcomeUpsertResult( |
| | 1 | 63 | | MatchOutcomeWriteDisposition.Updated, |
| | 1 | 64 | | ConvertToPersistedMatchOutcome(updated)); |
| | 1 | 65 | | } |
| | | 66 | | |
| | | 67 | | public async Task<IReadOnlyList<int>> GetIncompleteMatchdaysAsync( |
| | | 68 | | string communityContext, |
| | | 69 | | int currentMatchday, |
| | | 70 | | CancellationToken cancellationToken = default) |
| | | 71 | | { |
| | 1 | 72 | | var query = _firestoreDb.Collection(_matchOutcomesCollection) |
| | 1 | 73 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 74 | | .WhereEqualTo("competition", _competition) |
| | 1 | 75 | | .WhereLessThanOrEqualTo("matchday", currentMatchday); |
| | | 76 | | |
| | 1 | 77 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 78 | | var groupedOutcomes = snapshot.Documents |
| | 1 | 79 | | .Select(doc => doc.ConvertTo<FirestoreMatchOutcome>()) |
| | 1 | 80 | | .GroupBy(outcome => outcome.Matchday) |
| | 1 | 81 | | .ToDictionary(group => group.Key, group => group.ToList()); |
| | | 82 | | |
| | 1 | 83 | | var incompleteMatchdays = new List<int>(); |
| | 1 | 84 | | for (var matchday = 1; matchday <= currentMatchday; matchday++) |
| | | 85 | | { |
| | 1 | 86 | | if (!groupedOutcomes.TryGetValue(matchday, out var outcomes)) |
| | | 87 | | { |
| | 1 | 88 | | incompleteMatchdays.Add(matchday); |
| | 1 | 89 | | continue; |
| | | 90 | | } |
| | | 91 | | |
| | 1 | 92 | | var isComplete = string.Equals(_competition, CompetitionIds.Bundesliga2025_26, StringComparison.OrdinalIgnor |
| | 1 | 93 | | ? outcomes.Count >= ExpectedMatchesPerMatchday && |
| | 1 | 94 | | outcomes.All(outcome => string.Equals(outcome.Availability, nameof(MatchOutcomeAvailability.Completed) |
| | 1 | 95 | | : outcomes.Count > 0 && |
| | 0 | 96 | | outcomes.All(outcome => string.Equals(outcome.Availability, nameof(MatchOutcomeAvailability.Completed) |
| | | 97 | | |
| | 1 | 98 | | if (!isComplete) |
| | | 99 | | { |
| | 1 | 100 | | incompleteMatchdays.Add(matchday); |
| | | 101 | | } |
| | | 102 | | } |
| | | 103 | | |
| | 1 | 104 | | return incompleteMatchdays.AsReadOnly(); |
| | 1 | 105 | | } |
| | | 106 | | |
| | | 107 | | public async Task<IReadOnlyList<PersistedMatchOutcome>> GetMatchdayOutcomesAsync( |
| | | 108 | | int matchday, |
| | | 109 | | string communityContext, |
| | | 110 | | CancellationToken cancellationToken = default) |
| | | 111 | | { |
| | 1 | 112 | | var query = _firestoreDb.Collection(_matchOutcomesCollection) |
| | 1 | 113 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 114 | | .WhereEqualTo("competition", _competition) |
| | 1 | 115 | | .WhereEqualTo("matchday", matchday); |
| | | 116 | | |
| | 1 | 117 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 118 | | return snapshot.Documents |
| | 1 | 119 | | .Select(doc => doc.ConvertTo<FirestoreMatchOutcome>()) |
| | 1 | 120 | | .Select(ConvertToPersistedMatchOutcome) |
| | 1 | 121 | | .OrderBy(outcome => outcome.HomeTeam) |
| | 1 | 122 | | .ToList() |
| | 1 | 123 | | .AsReadOnly(); |
| | 1 | 124 | | } |
| | | 125 | | |
| | | 126 | | private static bool NeedsUpdate(FirestoreMatchOutcome existing, CollectedMatchOutcome outcome) |
| | | 127 | | { |
| | 1 | 128 | | return existing.HomeGoals != outcome.HomeGoals || |
| | 1 | 129 | | existing.AwayGoals != outcome.AwayGoals || |
| | 1 | 130 | | !string.Equals(existing.Availability, outcome.Availability.ToString(), StringComparison.Ordinal) || |
| | 1 | 131 | | existing.TippSpielId != outcome.TippSpielId || |
| | 1 | 132 | | existing.StartsAt.ToDateTimeOffset() != outcome.StartsAt.ToInstant().ToDateTimeOffset(); |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | private FirestoreMatchOutcome ToFirestoreMatchOutcome( |
| | | 136 | | CollectedMatchOutcome outcome, |
| | | 137 | | string communityContext, |
| | | 138 | | string documentId, |
| | | 139 | | Timestamp createdAt, |
| | | 140 | | Timestamp updatedAt) |
| | | 141 | | { |
| | 1 | 142 | | return new FirestoreMatchOutcome |
| | 1 | 143 | | { |
| | 1 | 144 | | Id = documentId, |
| | 1 | 145 | | HomeTeam = outcome.HomeTeam, |
| | 1 | 146 | | AwayTeam = outcome.AwayTeam, |
| | 1 | 147 | | StartsAt = ConvertToTimestamp(outcome.StartsAt), |
| | 1 | 148 | | Matchday = outcome.Matchday, |
| | 1 | 149 | | HomeGoals = outcome.HomeGoals, |
| | 1 | 150 | | AwayGoals = outcome.AwayGoals, |
| | 1 | 151 | | Availability = outcome.Availability.ToString(), |
| | 1 | 152 | | TippSpielId = outcome.TippSpielId, |
| | 1 | 153 | | CreatedAt = createdAt, |
| | 1 | 154 | | UpdatedAt = updatedAt, |
| | 1 | 155 | | Competition = _competition, |
| | 1 | 156 | | CommunityContext = communityContext |
| | 1 | 157 | | }; |
| | | 158 | | } |
| | | 159 | | |
| | | 160 | | private PersistedMatchOutcome ConvertToPersistedMatchOutcome(FirestoreMatchOutcome firestoreOutcome) |
| | | 161 | | { |
| | 1 | 162 | | return new PersistedMatchOutcome( |
| | 1 | 163 | | firestoreOutcome.CommunityContext, |
| | 1 | 164 | | firestoreOutcome.Competition, |
| | 1 | 165 | | firestoreOutcome.HomeTeam, |
| | 1 | 166 | | firestoreOutcome.AwayTeam, |
| | 1 | 167 | | ConvertFromTimestamp(firestoreOutcome.StartsAt), |
| | 1 | 168 | | firestoreOutcome.Matchday, |
| | 1 | 169 | | firestoreOutcome.HomeGoals, |
| | 1 | 170 | | firestoreOutcome.AwayGoals, |
| | 1 | 171 | | Enum.Parse<MatchOutcomeAvailability>(firestoreOutcome.Availability, ignoreCase: false), |
| | 1 | 172 | | firestoreOutcome.TippSpielId, |
| | 1 | 173 | | firestoreOutcome.CreatedAt.ToDateTimeOffset(), |
| | 1 | 174 | | firestoreOutcome.UpdatedAt.ToDateTimeOffset()); |
| | | 175 | | } |
| | | 176 | | |
| | | 177 | | private string BuildDocumentId(CollectedMatchOutcome outcome, string communityContext) |
| | | 178 | | { |
| | 1 | 179 | | var tippSpielId = outcome.TippSpielId ?? throw new InvalidOperationException( |
| | 1 | 180 | | $"Cannot persist match outcome for {outcome.HomeTeam} vs {outcome.AwayTeam} on matchday {outcome.Matchday} b |
| | | 181 | | |
| | 1 | 182 | | return string.Equals(_competition, CompetitionIds.Bundesliga2025_26, StringComparison.OrdinalIgnoreCase) |
| | 1 | 183 | | ? tippSpielId |
| | 1 | 184 | | : $"{_competition}_{communityContext}_{tippSpielId}"; |
| | | 185 | | } |
| | | 186 | | |
| | | 187 | | private static Timestamp ConvertToTimestamp(ZonedDateTime zonedDateTime) |
| | | 188 | | { |
| | 1 | 189 | | var instant = zonedDateTime.ToInstant(); |
| | 1 | 190 | | return Timestamp.FromDateTimeOffset(instant.ToDateTimeOffset()); |
| | | 191 | | } |
| | | 192 | | |
| | | 193 | | private static ZonedDateTime ConvertFromTimestamp(Timestamp timestamp) |
| | | 194 | | { |
| | 1 | 195 | | var instant = Instant.FromDateTimeOffset(timestamp.ToDateTimeOffset()); |
| | 1 | 196 | | return instant.InUtc(); |
| | | 197 | | } |
| | | 198 | | } |