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

namespace FacebookService.Infrastructure.EntityConfigurations;

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

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

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

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

        builder.Property<Guid>("_customerId")
            .HasColumnName("customer_id")
            .IsRequired();

        builder.Property<string>("_pageId")
            .HasColumnName("page_id")
            .HasMaxLength(50)
            .IsRequired();

        builder.Property(c => c.StatusId)
            .HasColumnName("status_id")
            .IsRequired();

        builder.Property<string>("_channel")
            .HasColumnName("channel")
            .HasMaxLength(50)
            .IsRequired();

        builder.Property<string?>("_assignedAgentId")
            .HasColumnName("assigned_agent_id")
            .HasMaxLength(100);

        builder.Property<DateTime?>("_lastMessageAt")
            .HasColumnName("last_message_at");

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

        // EN: Status navigation property / VI: Navigation property cho Status
        builder.HasOne(c => c.Status)
            .WithMany()
            .HasForeignKey(c => c.StatusId)
            .OnDelete(DeleteBehavior.Restrict);

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

        // EN: Owned messages collection / VI: Collection messages thuộc về
        var messagesNavigation = builder.Metadata.FindNavigation(nameof(Conversation.Messages));
        messagesNavigation?.SetPropertyAccessMode(PropertyAccessMode.Field);

        // EN: Indexes / VI: Các index
        builder.HasIndex("_customerId")
            .HasDatabaseName("idx_conversations_customer_id");

        builder.HasIndex("_pageId", "StatusId")
            .HasDatabaseName("idx_conversations_page_status");

        builder.HasIndex("_createdAt")
            .HasDatabaseName("idx_conversations_created_at");
    }
}
