#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;

/// <summary>
/// Fire-and-forget analytics sink — the mock inserts a <c>system_events</c> 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).
/// </summary>
internal sealed class AnalyticsSink(
    ApplicationDbContext db,
    ICurrentUser currentUser,
    IDateTimeProvider dateTimeProvider,
    ILogger<AnalyticsSink> logger) : IAnalyticsSink
{
    public async ValueTask EmitAsync(string name, object props, CancellationToken cancellationToken = default)
    {
        try
        {
            db.Set<SystemEvent>().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);
        }
    }
}
