| | | 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 | | /// <summary> |
| | | 10 | | /// Firebase Firestore implementation of the context repository. |
| | | 11 | | /// </summary> |
| | | 12 | | public class FirebaseContextRepository : IContextRepository |
| | | 13 | | { |
| | | 14 | | private readonly FirestoreDb _firestoreDb; |
| | | 15 | | private readonly ILogger<FirebaseContextRepository> _logger; |
| | | 16 | | private readonly string _contextDocumentsCollection; |
| | | 17 | | private readonly string _competition; |
| | | 18 | | |
| | 1 | 19 | | public FirebaseContextRepository( |
| | 1 | 20 | | FirestoreDb firestoreDb, |
| | 1 | 21 | | ILogger<FirebaseContextRepository> logger, |
| | 1 | 22 | | string? competition = null) |
| | | 23 | | { |
| | 1 | 24 | | _firestoreDb = firestoreDb ?? throw new ArgumentNullException(nameof(firestoreDb)); |
| | 1 | 25 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | | 26 | | |
| | 1 | 27 | | _contextDocumentsCollection = "context-documents"; |
| | 1 | 28 | | _competition = string.IsNullOrWhiteSpace(competition) |
| | 1 | 29 | | ? CompetitionIds.Bundesliga2025_26 |
| | 1 | 30 | | : competition.Trim(); |
| | | 31 | | |
| | 1 | 32 | | _logger.LogInformation("Firebase context repository initialized"); |
| | 1 | 33 | | } |
| | | 34 | | |
| | | 35 | | public async Task<int?> SaveContextDocumentAsync(string documentName, string content, string communityContext, Cance |
| | | 36 | | { |
| | | 37 | | try |
| | | 38 | | { |
| | | 39 | | // Get the latest version to check if content differs |
| | 1 | 40 | | var latestDocument = await GetLatestContextDocumentAsync(documentName, communityContext, cancellationToken); |
| | | 41 | | |
| | | 42 | | // If content is the same, don't save a new version |
| | 1 | 43 | | if (latestDocument != null && latestDocument.Content == content) |
| | | 44 | | { |
| | 1 | 45 | | _logger.LogInformation("Context document {DocumentName} content unchanged, skipping save", documentName) |
| | 1 | 46 | | return null; |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | // Determine the next version number |
| | 1 | 50 | | var nextVersion = latestDocument?.Version + 1 ?? 0; |
| | | 51 | | |
| | 1 | 52 | | var now = Timestamp.GetCurrentTimestamp(); |
| | 1 | 53 | | var documentId = BuildDocumentId(documentName, communityContext, nextVersion); |
| | | 54 | | |
| | 1 | 55 | | var firestoreDocument = new FirestoreContextDocument |
| | 1 | 56 | | { |
| | 1 | 57 | | Id = documentId, |
| | 1 | 58 | | DocumentName = documentName, |
| | 1 | 59 | | Content = content, |
| | 1 | 60 | | Version = nextVersion, |
| | 1 | 61 | | CreatedAt = now, |
| | 1 | 62 | | Competition = _competition, |
| | 1 | 63 | | CommunityContext = communityContext |
| | 1 | 64 | | }; |
| | | 65 | | |
| | 1 | 66 | | var docRef = _firestoreDb.Collection(_contextDocumentsCollection).Document(documentId); |
| | 1 | 67 | | await docRef.SetAsync(firestoreDocument, cancellationToken: cancellationToken); |
| | | 68 | | |
| | 1 | 69 | | _logger.LogInformation("Saved context document {DocumentName} version {Version} for community {CommunityCont |
| | 1 | 70 | | documentName, nextVersion, communityContext); |
| | | 71 | | |
| | 1 | 72 | | return nextVersion; |
| | | 73 | | } |
| | 0 | 74 | | catch (Exception ex) |
| | | 75 | | { |
| | 0 | 76 | | _logger.LogError(ex, "Failed to save context document {DocumentName} for community {CommunityContext}", |
| | 0 | 77 | | documentName, communityContext); |
| | 0 | 78 | | throw; |
| | | 79 | | } |
| | 1 | 80 | | } |
| | | 81 | | |
| | | 82 | | public async Task<ContextDocument?> GetLatestContextDocumentAsync(string documentName, string communityContext, Canc |
| | | 83 | | { |
| | | 84 | | try |
| | | 85 | | { |
| | 1 | 86 | | var query = _firestoreDb.Collection(_contextDocumentsCollection) |
| | 1 | 87 | | .WhereEqualTo("documentName", documentName) |
| | 1 | 88 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 89 | | .WhereEqualTo("competition", _competition) |
| | 1 | 90 | | .OrderByDescending("version") |
| | 1 | 91 | | .Limit(1); |
| | | 92 | | |
| | 1 | 93 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 94 | | |
| | 1 | 95 | | if (!snapshot.Documents.Any()) |
| | | 96 | | { |
| | 1 | 97 | | return null; |
| | | 98 | | } |
| | | 99 | | |
| | 1 | 100 | | var firestoreDoc = snapshot.Documents.First().ConvertTo<FirestoreContextDocument>(); |
| | 1 | 101 | | return ConvertToContextDocument(firestoreDoc); |
| | | 102 | | } |
| | 0 | 103 | | catch (Exception ex) |
| | | 104 | | { |
| | 0 | 105 | | _logger.LogError(ex, "Failed to retrieve latest context document {DocumentName} for community {CommunityCont |
| | 0 | 106 | | documentName, communityContext); |
| | 0 | 107 | | throw; |
| | | 108 | | } |
| | 1 | 109 | | } |
| | | 110 | | |
| | | 111 | | public async Task<ContextDocument?> GetContextDocumentAsync(string documentName, int version, string communityContex |
| | | 112 | | { |
| | | 113 | | try |
| | | 114 | | { |
| | 1 | 115 | | var documentId = BuildDocumentId(documentName, communityContext, version); |
| | 1 | 116 | | var docRef = _firestoreDb.Collection(_contextDocumentsCollection).Document(documentId); |
| | 1 | 117 | | var snapshot = await docRef.GetSnapshotAsync(cancellationToken); |
| | | 118 | | |
| | 1 | 119 | | if (!snapshot.Exists) |
| | | 120 | | { |
| | 1 | 121 | | return null; |
| | | 122 | | } |
| | | 123 | | |
| | 1 | 124 | | var firestoreDoc = snapshot.ConvertTo<FirestoreContextDocument>(); |
| | 1 | 125 | | return ConvertToContextDocument(firestoreDoc); |
| | | 126 | | } |
| | 0 | 127 | | catch (Exception ex) |
| | | 128 | | { |
| | 0 | 129 | | _logger.LogError(ex, "Failed to retrieve context document {DocumentName} version {Version} for community {Co |
| | 0 | 130 | | documentName, version, communityContext); |
| | 0 | 131 | | throw; |
| | | 132 | | } |
| | 1 | 133 | | } |
| | | 134 | | |
| | | 135 | | public async Task<ContextDocument?> GetContextDocumentByTimestampAsync( |
| | | 136 | | string documentName, |
| | | 137 | | DateTimeOffset createdAtOrEarlier, |
| | | 138 | | string communityContext, |
| | | 139 | | CancellationToken cancellationToken = default) |
| | | 140 | | { |
| | | 141 | | try |
| | | 142 | | { |
| | 1 | 143 | | var query = _firestoreDb.Collection(_contextDocumentsCollection) |
| | 1 | 144 | | .WhereEqualTo("documentName", documentName) |
| | 1 | 145 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 146 | | .WhereEqualTo("competition", _competition) |
| | 1 | 147 | | .WhereLessThanOrEqualTo("createdAt", Timestamp.FromDateTime(createdAtOrEarlier.UtcDateTime)) |
| | 1 | 148 | | .OrderByDescending("createdAt") |
| | 1 | 149 | | .OrderByDescending("version") |
| | 1 | 150 | | .Limit(1); |
| | | 151 | | |
| | 1 | 152 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 153 | | |
| | 1 | 154 | | if (!snapshot.Documents.Any()) |
| | | 155 | | { |
| | 1 | 156 | | return null; |
| | | 157 | | } |
| | | 158 | | |
| | 1 | 159 | | var firestoreDoc = snapshot.Documents.First().ConvertTo<FirestoreContextDocument>(); |
| | 1 | 160 | | return ConvertToContextDocument(firestoreDoc); |
| | | 161 | | } |
| | 0 | 162 | | catch (Exception ex) |
| | | 163 | | { |
| | 0 | 164 | | _logger.LogError( |
| | 0 | 165 | | ex, |
| | 0 | 166 | | "Failed to retrieve context document {DocumentName} at timestamp {CreatedAt} for community {CommunityCon |
| | 0 | 167 | | documentName, |
| | 0 | 168 | | createdAtOrEarlier, |
| | 0 | 169 | | communityContext); |
| | 0 | 170 | | throw; |
| | | 171 | | } |
| | 1 | 172 | | } |
| | | 173 | | |
| | | 174 | | public async Task<IReadOnlyList<string>> GetContextDocumentNamesAsync(string communityContext, CancellationToken can |
| | | 175 | | { |
| | | 176 | | try |
| | | 177 | | { |
| | 1 | 178 | | var query = _firestoreDb.Collection(_contextDocumentsCollection) |
| | 1 | 179 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 180 | | .WhereEqualTo("competition", _competition) |
| | 1 | 181 | | .Select("documentName"); |
| | | 182 | | |
| | 1 | 183 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 184 | | |
| | 1 | 185 | | var documentNames = snapshot.Documents |
| | 1 | 186 | | .Select(doc => doc.GetValue<string>("documentName")) |
| | 1 | 187 | | .Distinct() |
| | 1 | 188 | | .OrderBy(name => name, StringComparer.Ordinal) |
| | 1 | 189 | | .ToList() |
| | 1 | 190 | | .AsReadOnly(); |
| | | 191 | | |
| | 1 | 192 | | return documentNames; |
| | | 193 | | } |
| | 0 | 194 | | catch (Exception ex) |
| | | 195 | | { |
| | 0 | 196 | | _logger.LogError(ex, "Failed to retrieve context document names for community {CommunityContext}", community |
| | 0 | 197 | | throw; |
| | | 198 | | } |
| | 1 | 199 | | } |
| | | 200 | | |
| | | 201 | | public async Task<IReadOnlyList<ContextDocument>> GetContextDocumentVersionsAsync(string documentName, string commun |
| | | 202 | | { |
| | | 203 | | try |
| | | 204 | | { |
| | 1 | 205 | | var query = _firestoreDb.Collection(_contextDocumentsCollection) |
| | 1 | 206 | | .WhereEqualTo("documentName", documentName) |
| | 1 | 207 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 208 | | .WhereEqualTo("competition", _competition) |
| | 1 | 209 | | .OrderBy("version"); |
| | | 210 | | |
| | 1 | 211 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 212 | | |
| | 1 | 213 | | var documents = snapshot.Documents |
| | 1 | 214 | | .Select(doc => doc.ConvertTo<FirestoreContextDocument>()) |
| | 1 | 215 | | .Select(ConvertToContextDocument) |
| | 1 | 216 | | .ToList() |
| | 1 | 217 | | .AsReadOnly(); |
| | | 218 | | |
| | 1 | 219 | | return documents; |
| | | 220 | | } |
| | 0 | 221 | | catch (Exception ex) |
| | | 222 | | { |
| | 0 | 223 | | _logger.LogError(ex, "Failed to retrieve context document versions for {DocumentName} in community {Communit |
| | 0 | 224 | | documentName, communityContext); |
| | 0 | 225 | | throw; |
| | | 226 | | } |
| | 1 | 227 | | } |
| | | 228 | | |
| | | 229 | | public async Task<bool> UpdateContextDocumentVersionAsync(string documentName, int version, string newContent, strin |
| | | 230 | | { |
| | | 231 | | try |
| | | 232 | | { |
| | 1 | 233 | | var documentId = BuildDocumentId(documentName, communityContext, version); |
| | 1 | 234 | | var docRef = _firestoreDb.Collection(_contextDocumentsCollection).Document(documentId); |
| | | 235 | | |
| | | 236 | | // Check if document exists |
| | 1 | 237 | | var snapshot = await docRef.GetSnapshotAsync(cancellationToken); |
| | 1 | 238 | | if (!snapshot.Exists) |
| | | 239 | | { |
| | 1 | 240 | | _logger.LogWarning("Cannot update non-existent document {DocumentId}", documentId); |
| | 1 | 241 | | return false; |
| | | 242 | | } |
| | | 243 | | |
| | | 244 | | // Update only the content field |
| | 1 | 245 | | var updates = new Dictionary<string, object> |
| | 1 | 246 | | { |
| | 1 | 247 | | ["content"] = newContent |
| | 1 | 248 | | }; |
| | | 249 | | |
| | 1 | 250 | | await docRef.UpdateAsync(updates, cancellationToken: cancellationToken); |
| | | 251 | | |
| | 1 | 252 | | _logger.LogInformation("Updated content for context document {DocumentName} version {Version} in community { |
| | 1 | 253 | | documentName, version, communityContext); |
| | | 254 | | |
| | 1 | 255 | | return true; |
| | | 256 | | } |
| | 0 | 257 | | catch (Exception ex) |
| | | 258 | | { |
| | 0 | 259 | | _logger.LogError(ex, "Failed to update context document {DocumentName} version {Version} in community {Commu |
| | 0 | 260 | | documentName, version, communityContext); |
| | 0 | 261 | | throw; |
| | | 262 | | } |
| | 1 | 263 | | } |
| | | 264 | | |
| | | 265 | | private static ContextDocument ConvertToContextDocument(FirestoreContextDocument firestoreDoc) |
| | | 266 | | { |
| | 1 | 267 | | return new ContextDocument( |
| | 1 | 268 | | firestoreDoc.DocumentName, |
| | 1 | 269 | | firestoreDoc.Content, |
| | 1 | 270 | | firestoreDoc.Version, |
| | 1 | 271 | | firestoreDoc.CreatedAt.ToDateTimeOffset()); |
| | | 272 | | } |
| | | 273 | | |
| | | 274 | | private string BuildDocumentId(string documentName, string communityContext, int version) |
| | | 275 | | { |
| | 1 | 276 | | return string.Equals(_competition, CompetitionIds.Bundesliga2025_26, StringComparison.OrdinalIgnoreCase) |
| | 1 | 277 | | ? $"{documentName}_{communityContext}_{version}" |
| | 1 | 278 | | : $"{_competition}_{documentName}_{communityContext}_{version}"; |
| | | 279 | | } |
| | | 280 | | } |