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

namespace FacebookService.Infrastructure.EntityConfigurations;

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

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

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

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

        builder.Property<string>("_senderId")
            .HasColumnName("sender_id")
            .HasMaxLength(50)
            .IsRequired();

        builder.Property<string>("_content")
            .HasColumnName("content")
            .IsRequired();

        builder.Property(m => m.MessageTypeId)
            .HasColumnName("message_type_id")
            .IsRequired();

        builder.Property(m => m.DirectionId)
            .HasColumnName("direction_id")
            .IsRequired();

        // EN: Metadata as JSONB / VI: Metadata như JSONB
        builder.Property<Dictionary<string, object>>("_metadata")
            .HasColumnName("metadata")
            .HasColumnType("jsonb");

        builder.Property<DateTime>("_sentAt")
            .HasColumnName("sent_at")
            .IsRequired();

        builder.Property<string?>("_facebookMessageId")
            .HasColumnName("facebook_message_id")
            .HasMaxLength(100);

        // EN: Navigation properties / VI: Navigation properties
        builder.HasOne(m => m.MessageType)
            .WithMany()
            .HasForeignKey(m => m.MessageTypeId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(m => m.Direction)
            .WithMany()
            .HasForeignKey(m => m.DirectionId)
            .OnDelete(DeleteBehavior.Restrict);

        // EN: Indexes / VI: Các index
        builder.HasIndex("ConversationId", "_sentAt")
            .HasDatabaseName("idx_messages_conversation_sent");

        builder.HasIndex("_facebookMessageId")
            .HasDatabaseName("idx_messages_fb_message_id");
    }
}
