using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using WhatsAppService.Domain.AggregatesModel.AIAgentAggregate;
using WhatsAppService.Domain.AggregatesModel.AutomationFlowAggregate;
using WhatsAppService.Domain.AggregatesModel.ConversationAggregate;
using WhatsAppService.Domain.AggregatesModel.CustomerAggregate;
using WhatsAppService.Domain.AggregatesModel.SampleAggregate;
using WhatsAppService.Domain.AggregatesModel.WhatsAppAccountAggregate;
using WhatsAppService.Domain.SeedWork;
using WhatsAppService.Infrastructure.EntityConfigurations;

namespace WhatsAppService.Infrastructure;

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

    // EN: Sample (template) / VI: Sample (mẫu)
    public DbSet<Sample> Samples => Set<Sample>();

    // EN: WhatsApp Accounts / VI: Tài khoản WhatsApp
    public DbSet<WhatsAppAccount> WhatsAppAccounts => Set<WhatsAppAccount>();
    
    // EN: Customers / VI: Khách hàng
    public DbSet<Customer> Customers => Set<Customer>();
    
    // EN: Conversations & Messages / VI: Hội thoại & Tin nhắn
    public DbSet<Conversation> Conversations => Set<Conversation>();
    public DbSet<Message> Messages => Set<Message>();
    
    // EN: Automation Flows / VI: Luồng tự động
    public DbSet<AutomationFlow> AutomationFlows => Set<AutomationFlow>();
    public DbSet<FlowStep> FlowSteps => Set<FlowStep>();
    
    // EN: AI Agents / VI: AI Agents
    public DbSet<AIAgent> AIAgents => Set<AIAgent>();

    /// <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 WhatsAppServiceContext(DbContextOptions<WhatsAppServiceContext> options) : base(options)
    {
        _mediator = null!;
    }

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

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // EN: Apply entity configurations
        // VI: Áp dụng các cấu hình entity
        
        // Sample (template)
        modelBuilder.ApplyConfiguration(new SampleEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new SampleStatusEntityTypeConfiguration());
        
        // WhatsApp Account
        modelBuilder.ApplyConfiguration(new WhatsAppAccountEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new WhatsAppAccountStatusEntityTypeConfiguration());
        
        // Customer
        modelBuilder.ApplyConfiguration(new CustomerEntityTypeConfiguration());
        
        // Conversation & Message
        modelBuilder.ApplyConfiguration(new ConversationEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new MessageEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new ConversationStatusEntityTypeConfiguration());
        
        // Automation Flow
        modelBuilder.ApplyConfiguration(new AutomationFlowEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new FlowStepEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new TriggerTypeEntityTypeConfiguration());
        
        // AI Agent
        modelBuilder.ApplyConfiguration(new AIAgentEntityTypeConfiguration());
    }

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