namespace WalletService.Infrastructure;

using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using WalletService.Domain.AggregatesModel.PointAccountAggregate;
using WalletService.Domain.AggregatesModel.WalletAggregate;
using WalletService.Domain.SeedWork;

/// <summary>
/// EN: Database context for Wallet Service with Unit of Work pattern
/// VI: Database context cho Wallet Service với pattern Unit of Work
/// </summary>
public class WalletServiceContext : DbContext, IUnitOfWork
{
    private readonly IMediator _mediator;
    private IDbContextTransaction? _currentTransaction;

    public DbSet<Wallet> Wallets { get; set; } = null!;
    public DbSet<WalletItem> WalletItems { get; set; } = null!;
    public DbSet<WalletTransaction> WalletTransactions { get; set; } = null!;
    public DbSet<HoldItem> WalletHolds { get; set; } = null!;
    public DbSet<PointAccount> PointAccounts { get; set; } = null!;
    public DbSet<PointTransaction> PointTransactions { get; set; } = null!;

    public bool HasActiveTransaction => _currentTransaction != null;

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // EN: Apply all entity configurations
        // VI: Áp dụng tất cả các cấu hình entity
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(WalletServiceContext).Assembly);
    }

    /// <summary>
    /// EN: Save changes and dispatch domain events
    /// VI: Lưu thay đổi và dispatch domain events
    /// </summary>
    public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default)
    {
        // EN: Dispatch domain events after saving
        // VI: Dispatch domain events sau khi lưu
        await DispatchDomainEventsAsync();

        // EN: Save changes to database
        // VI: Lưu thay đổi vào database
        var result = await base.SaveChangesAsync(cancellationToken);
        return result > 0;
    }

    /// <summary>
    /// EN: Begin a new transaction
    /// VI: Bắt đầu transaction mới
    /// </summary>
    public async Task<IDbContextTransaction?> BeginTransactionAsync()
    {
        if (_currentTransaction != null) return null;

        _currentTransaction = await Database.BeginTransactionAsync();
        return _currentTransaction;
    }

    /// <summary>
    /// EN: Commit the current transaction
    /// VI: Commit transaction hiện tại
    /// </summary>
    public async Task CommitTransactionAsync(IDbContextTransaction transaction)
    {
        if (transaction == null) throw new ArgumentNullException(nameof(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;
            }
        }
    }

    /// <summary>
    /// EN: Rollback the current transaction
    /// VI: Rollback transaction hiện tại
    /// </summary>
    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);
        }
    }
}
