using MediatR;
using Microsoft.EntityFrameworkCore;
using WhatsAppService.Infrastructure;

namespace WhatsAppService.API.Application.Behaviors;

/// <summary>
/// EN: MediatR behavior for handling database transactions.
/// VI: MediatR behavior để xử lý database transactions.
/// </summary>
/// <typeparam name="TRequest">EN: Request type / VI: Loại request</typeparam>
/// <typeparam name="TResponse">EN: Response type / VI: Loại response</typeparam>
public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly WhatsAppServiceContext _dbContext;
    private readonly ILogger<TransactionBehavior<TRequest, TResponse>> _logger;

    public TransactionBehavior(
        WhatsAppServiceContext dbContext,
        ILogger<TransactionBehavior<TRequest, TResponse>> logger)
    {
        _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<TResponse> Handle(
        TRequest request,
        RequestHandlerDelegate<TResponse> next,
        CancellationToken cancellationToken)
    {
        var requestName = typeof(TRequest).Name;

        // EN: Skip transaction for queries (read operations)
        // VI: Bỏ qua transaction cho queries (các thao tác đọc)
        if (requestName.EndsWith("Query"))
        {
            return await next();
        }

        // EN: Skip if already in a transaction
        // VI: Bỏ qua nếu đã trong transaction
        if (_dbContext.HasActiveTransaction)
        {
            return await next();
        }

        var strategy = _dbContext.Database.CreateExecutionStrategy();

        return await strategy.ExecuteAsync(async () =>
        {
            await using var transaction = await _dbContext.BeginTransactionAsync();

            _logger.LogInformation(
                "Begin transaction {TransactionId} for {RequestName} / Bắt đầu transaction {TransactionId} cho {RequestName}",
                transaction?.TransactionId, requestName);

            try
            {
                var response = await next();

                if (transaction != null)
                {
                    await _dbContext.CommitTransactionAsync(transaction);

                    _logger.LogInformation(
                        "Committed transaction {TransactionId} for {RequestName} / Đã commit transaction {TransactionId} cho {RequestName}",
                        transaction.TransactionId, requestName);
                }

                return response;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex,
                    "Error during transaction {TransactionId} for {RequestName} / Lỗi trong transaction {TransactionId} cho {RequestName}",
                    transaction?.TransactionId, requestName);

                _dbContext.RollbackTransaction();
                throw;
            }
        });
    }
}
