using MediatR.Pipeline;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.Application.Common.Behaviours;

public class LoggingBehaviour<TRequest> : IRequestPreProcessor<TRequest> where TRequest : notnull
{
    private readonly ILogger _logger;
    private readonly ICurrentUserService _currentUserService;

    public LoggingBehaviour(ILogger<TRequest> logger, ICurrentUserService currentUserService)
    {
        _logger = logger;
        _currentUserService = currentUserService;
    }

    public async Task Process(TRequest request, CancellationToken cancellationToken)
    {
        var requestName = typeof(TRequest).Name;
        var userId = _currentUserService.UserId ?? string.Empty;
        var safeLog = request?.ToString() ?? "";
        if (safeLog.Length > 2000)
            safeLog = safeLog[..2000] + "... [TRUNCATED]";
        _logger.LogInformation("Request: {Name} {UserId} {Request}",
            requestName, userId, safeLog);
    }
}
