using Femto.Common.Domain;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Femto.Common.Infrastructure;

public class SaveChangesPipelineBehaviour<TRequest, TResponse>(
    DbContext context,
    IPublisher publisher,
    ILogger<SaveChangesPipelineBehaviour<TRequest, TResponse>> logger
) : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    public async Task<TResponse> Handle(
        TRequest request,
        RequestHandlerDelegate<TResponse> next,
        CancellationToken cancellationToken
    )
    {
        var response = await next(cancellationToken);
        if (context.ChangeTracker.HasChanges())
        {
            await context.EmitDomainEvents(logger, publisher, cancellationToken);
            logger.LogDebug("saving changes");
            await context.SaveChangesAsync(cancellationToken);
        }
        return response;
    }
}
