using OmsorgCore.Application.Abstractions;
using OmsorgCore.Domain.Entities;
using OmsorgCore.Domain.Enums;
using OmsorgCore.Engine.Events;

namespace OmsorgCore.Engine.Handlers;

/// <summary>
/// Persistiert jedes dispatchte <see cref="AuditEvent"/> als AuditLogEntry mit
/// Category = BehavioralEvent. Geht ausschließlich über IAuditLogRepository (Application-Abstraktion) -
/// Engine kennt Infrastructure/OmsorgCoreDbContext nicht.
/// </summary>
public class AuditEventHandler : IDomainEventHandler<AuditEvent>
{
    private readonly IAuditLogRepository _auditLogRepository;

    public AuditEventHandler(IAuditLogRepository auditLogRepository)
    {
        _auditLogRepository = auditLogRepository;
    }

    public async Task HandleAsync(AuditEvent domainEvent, CancellationToken cancellationToken = default)
    {
        await _auditLogRepository.AddAsync(new AuditLogEntry
        {
            OccurredAtUtc = domainEvent.OccurredAt,
            ActorUserId = domainEvent.ActorUserId,
            ActorUsername = domainEvent.ActorUsername,
            IpAddress = domainEvent.IpAddress,
            Category = AuditEventCategory.BehavioralEvent,
            Action = domainEvent.Action,
            Details = domainEvent.Details
        }, cancellationToken);

        await _auditLogRepository.SaveChangesAsync(cancellationToken);
    }
}
