using Femto.Modules.Auth.Data;
using MediatR;

namespace Femto.Modules.Auth.Infrastructure;

internal class SaveChangesPipelineBehaviour<TRequest, TResponse>(AuthContext context)
    : 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.SaveChangesAsync(cancellationToken);

        return response;
    }
}
