#nullable enable using System.Text.Json; using Baya.Application.Contracts.Analytics; using Baya.Application.Contracts.Common; using Baya.Domain.Entities.Analytics; using Microsoft.Extensions.Logging; namespace Baya.Infrastructure.Persistence.Services.Analytics; /// /// Fire-and-forget analytics sink — the mock inserts a system_events row. A failure is logged and /// swallowed so it can never surface to, or slow, the caller's operation. Compliance facts never come /// here (they go to the audit trail). /// internal sealed class AnalyticsSink( ApplicationDbContext db, ICurrentUser currentUser, IDateTimeProvider dateTimeProvider, ILogger logger) : IAnalyticsSink { public async ValueTask EmitAsync(string name, object props, CancellationToken cancellationToken = default) { try { db.Set().Add(new SystemEvent { Name = name, PropsJson = JsonSerializer.Serialize(props), UserId = currentUser.UserId, OccurredAt = dateTimeProvider.UtcNow }); await db.SaveChangesAsync(cancellationToken); } catch (Exception ex) { logger.LogWarning(ex, "Analytics emit failed for event {EventName}", name); } } }