using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using CatalogService.Domain.AggregatesModel.ProductAggregate;
using CatalogService.Domain.SeedWork;
using CatalogService.Infrastructure.EntityConfigurations;

namespace CatalogService.Infrastructure;

/// <summary>
/// EN: Tenant provider interface for CatalogContext global query filters.
/// VI: Interface tenant provider cho global query filters của CatalogContext.
/// </summary>
public interface ICatalogTenantProvider
{
    Guid? GetCurrentShopId();
    bool ShouldBypassTenantFilter();
}

/// <summary>
/// EN: EF Core DbContext for CatalogService with multi-tenant global query filters.
/// VI: EF Core DbContext cho CatalogService với global query filters đa tenant.
/// </summary>
public class CatalogContext : DbContext, IUnitOfWork
{
    private readonly IMediator _mediator;
    private readonly ICatalogTenantProvider? _tenantProvider;
    private IDbContextTransaction? _currentTransaction;

    /// <summary>
    /// EN: Products table.
    /// VI: Bảng Products.
    /// </summary>
    public DbSet<Product> Products => Set<Product>();

    /// <summary>
    /// EN: Categories table.
    /// VI: Bảng Categories.
    /// </summary>
    public DbSet<Category> Categories => Set<Category>();

    /// <summary>
    /// EN: Read-only access to current transaction.
    /// VI: Truy cập chỉ đọc đến transaction hiện tại.
    /// </summary>
    public IDbContextTransaction? CurrentTransaction => _currentTransaction;

    /// <summary>
    /// EN: Check if there is an active transaction.
    /// VI: Kiểm tra xem có transaction đang hoạt động không.
    /// </summary>
    public bool HasActiveTransaction => _currentTransaction != null;

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

        System.Diagnostics.Debug.WriteLine("CatalogContext::ctor - " + GetHashCode());
    }

    /// <summary>
    /// EN: Constructor with tenant provider for multi-tenant filtering.
    /// VI: Constructor với tenant provider cho filtering đa tenant.
    /// </summary>
    public CatalogContext(
        DbContextOptions<CatalogContext> options,
        IMediator mediator,
        ICatalogTenantProvider tenantProvider) : base(options)
    {
        _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        _tenantProvider = tenantProvider;

        System.Diagnostics.Debug.WriteLine("CatalogContext::ctor (tenant) - " + GetHashCode());
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // EN: Apply entity configurations
        // VI: Áp dụng các cấu hình entity
        modelBuilder.ApplyConfiguration(new ProductEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new CategoryEntityTypeConfiguration());

        // EN: Ignore ProductType so EF Core does NOT auto-discover Product.TypeId as a FK.
        //     ProductType is a DDD Enumeration resolved in-memory; the product_types table
        //     is seeded by the initial migration and not managed at runtime.
        // VI: Ignore ProductType để EF Core KHÔNG tự phát hiện Product.TypeId là FK.
        //     ProductType là DDD Enumeration được resolve trong bộ nhớ; bảng product_types
        //     được seed bởi migration khởi tạo và không được quản lý lúc runtime.
        modelBuilder.Ignore<ProductType>();

        // EN: Global query filters for tenant isolation (shop-level).
        //     Both Products and Categories belong to a shop.
        // VI: Global query filters cho cách ly tenant (cấp shop).
        //     Cả Products và Categories đều thuộc về một shop.
        modelBuilder.Entity<Product>().HasQueryFilter(p =>
            _tenantProvider == null
            || _tenantProvider.ShouldBypassTenantFilter()
            || _tenantProvider.GetCurrentShopId() == null
            || p.ShopId == _tenantProvider.GetCurrentShopId());

        modelBuilder.Entity<Category>().HasQueryFilter(c =>
            _tenantProvider == null
            || _tenantProvider.ShouldBypassTenantFilter()
            || _tenantProvider.GetCurrentShopId() == null
            || c.ShopId == _tenantProvider.GetCurrentShopId());
    }

    /// <summary>
    /// EN: Save entities and dispatch domain events.
    /// VI: Lưu entities và dispatch domain events.
    /// </summary>
    public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default)
    {
        // EN: Dispatch domain events before saving (side effects)
        // VI: Dispatch domain events trước khi lưu (side effects)
        await DispatchDomainEventsAsync();

        // EN: Save changes to database
        // VI: Lưu thay đổi vào database
        await base.SaveChangesAsync(cancellationToken);

        return true;
    }

    /// <summary>
    /// EN: Begin a new transaction if none is active.
    /// VI: Bắt đầu một transaction mới nếu không có transaction nào đang hoạt động.
    /// </summary>
    public async Task<IDbContextTransaction?> BeginTransactionAsync()
    {
        if (_currentTransaction != null) return null;

        _currentTransaction = await Database.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted);

        return _currentTransaction;
    }

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

    /// <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;
            }
        }
    }

    /// <summary>
    /// EN: Dispatch all domain events from tracked entities.
    /// VI: Dispatch tất cả domain events từ các entities đang được track.
    /// </summary>
    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);
        }
    }
}
