using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using AdsServingService.Domain.AggregatesModel.AuctionAggregate;
using AdsServingService.Domain.AggregatesModel.PacingAggregate;
using AdsServingService.Domain.AggregatesModel.FrequencyAggregate;
using AdsServingService.Domain.SeedWork;

namespace AdsServingService.Infrastructure;

/// <summary>
/// EN: EF Core DbContext for AdsServingService.
/// VI: EF Core DbContext cho AdsServingService.
/// </summary>
public class AdsServingServiceContext : DbContext, IUnitOfWork
{
    private readonly IMediator _mediator;
    private IDbContextTransaction? _currentTransaction;

    public DbSet<Auction> Auctions => Set<Auction>();
    public DbSet<BudgetPacer> BudgetPacers => Set<BudgetPacer>();
    public DbSet<FrequencyCap> FrequencyCaps => Set<FrequencyCap>();

    public IDbContextTransaction? CurrentTransaction => _currentTransaction;
    public bool HasActiveTransaction => _currentTransaction != null;

    public AdsServingServiceContext(DbContextOptions<AdsServingServiceContext> options) : base(options)
    {
        _mediator = null!;
    }

    public AdsServingServiceContext(DbContextOptions<AdsServingServiceContext> options, IMediator mediator) : base(options)
    {
        _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // EN: Apply all entity configurations from current assembly
        // VI: Áp dụng tất cả entity configurations từ assembly hiện tại
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(AdsServingServiceContext).Assembly);
    }

    public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default)
    {
        await DispatchDomainEventsAsync();
        await base.SaveChangesAsync(cancellationToken);
        return true;
    }

    public async Task<IDbContextTransaction?> BeginTransactionAsync()
    {
        if (_currentTransaction != null) return null;
        _currentTransaction = await Database.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted);
        return _currentTransaction;
    }

    public async Task CommitTransactionAsync(IDbContextTransaction transaction)
    {
        ArgumentNullException.ThrowIfNull(transaction);
        if (transaction != _currentTransaction)
            throw new InvalidOperationException($"Transaction {transaction.TransactionId} is not current");

        try
        {
            await SaveChangesAsync();
            await transaction.CommitAsync();
        }
        catch
        {
            RollbackTransaction();
            throw;
        }
        finally
        {
            if (_currentTransaction != null)
            {
                _currentTransaction.Dispose();
                _currentTransaction = null;
            }
        }
    }

    public void RollbackTransaction()
    {
        try
        {
            _currentTransaction?.Rollback();
        }
        finally
        {
            if (_currentTransaction != null)
            {
                _currentTransaction.Dispose();
                _currentTransaction = null;
            }
        }
    }

    private async Task DispatchDomainEventsAsync()
    {
        var domainEntities = ChangeTracker
            .Entries<Entity>()
            .Where(x => x.Entity.DomainEvents.Any())
            .ToList();

        var domainEvents = domainEntities
            .SelectMany(x => x.Entity.DomainEvents)
            .ToList();

        domainEntities.ForEach(entity => entity.Entity.ClearDomainEvents());

        foreach (var domainEvent in domainEvents)
        {
            await _mediator.Publish(domainEvent);
        }
    }
}
