using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using FacebookService.Domain.AggregatesModel.CustomerAggregate;
using FacebookService.Domain.AggregatesModel.ConversationAggregate;
using FacebookService.Domain.AggregatesModel.ChatbotAggregate;
using FacebookService.Domain.SeedWork;
using FacebookService.Infrastructure.EntityConfigurations;

namespace FacebookService.Infrastructure;

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

    #region DbSets

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

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

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

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

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

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

    #endregion

    #region Enumeration DbSets

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

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

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

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

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

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

    #endregion

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

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

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

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

        // Conversation aggregate
        modelBuilder.ApplyConfiguration(new ConversationEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new MessageEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new ConversationStatusEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new MessageTypeEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new MessageDirectionEntityTypeConfiguration());

        // Chatbot aggregate
        modelBuilder.ApplyConfiguration(new ChatbotFlowEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new FlowNodeEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new AIChatbotConfigEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new FlowTriggerTypeEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new NodeTypeEntityTypeConfiguration());
        modelBuilder.ApplyConfiguration(new AIProviderEntityTypeConfiguration());
    }

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