using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using FacebookService.Domain.AggregatesModel.ChatbotAggregate;

namespace FacebookService.Infrastructure.EntityConfigurations;

/// <summary>
/// EN: EF Core configuration for ChatbotFlow entity.
/// VI: Cấu hình EF Core cho entity ChatbotFlow.
/// </summary>
public class ChatbotFlowEntityTypeConfiguration : IEntityTypeConfiguration<ChatbotFlow>
{
    public void Configure(EntityTypeBuilder<ChatbotFlow> builder)
    {
        // EN: Table name / VI: Tên bảng
        builder.ToTable("chatbot_flows");

        // EN: Primary key / VI: Khóa chính
        builder.HasKey(f => f.Id);

        // EN: Ignore domain events / VI: Bỏ qua domain events
        builder.Ignore(f => f.DomainEvents);

        // EN: Properties / VI: Các thuộc tính
        builder.Property(f => f.Id)
            .HasColumnName("id")
            .IsRequired();

        builder.Property<string>("_name")
            .HasColumnName("name")
            .HasMaxLength(255)
            .IsRequired();

        builder.Property<Guid>("_shopId")
            .HasColumnName("shop_id")
            .IsRequired();

        builder.Property(f => f.TriggerTypeId)
            .HasColumnName("trigger_type_id")
            .IsRequired();

        builder.Property<string>("_triggerValue")
            .HasColumnName("trigger_value")
            .HasMaxLength(255)
            .IsRequired();

        builder.Property<bool>("_isActive")
            .HasColumnName("is_active")
            .IsRequired();

        builder.Property<DateTime>("_createdAt")
            .HasColumnName("created_at")
            .IsRequired();

        builder.Property<DateTime?>("_updatedAt")
            .HasColumnName("updated_at");

        // EN: Trigger type navigation / VI: Navigation cho trigger type
        builder.HasOne(f => f.TriggerType)
            .WithMany()
            .HasForeignKey(f => f.TriggerTypeId)
            .OnDelete(DeleteBehavior.Restrict);

        // EN: Nodes relationship / VI: Quan hệ với Nodes
        builder.HasMany(f => f.Nodes)
            .WithOne()
            .HasForeignKey("FlowId")
            .OnDelete(DeleteBehavior.Cascade);

        var nodesNavigation = builder.Metadata.FindNavigation(nameof(ChatbotFlow.Nodes));
        nodesNavigation?.SetPropertyAccessMode(PropertyAccessMode.Field);

        // EN: Indexes / VI: Các index
        builder.HasIndex("_shopId", "_triggerValue")
            .IsUnique()
            .HasDatabaseName("idx_chatbot_flows_shop_trigger");

        builder.HasIndex("_shopId", "_isActive")
            .HasDatabaseName("idx_chatbot_flows_shop_active");
    }
}
