using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using SocialService.Domain.AggregatesModel.RelationshipAggregate;

namespace SocialService.Infrastructure.EntityConfigurations;

/// <summary>
/// EN: EF Core configuration for Relationship entity.
/// VI: Cấu hình EF Core cho Relationship entity.
/// </summary>
public class RelationshipEntityTypeConfiguration : IEntityTypeConfiguration<Relationship>
{
    public void Configure(EntityTypeBuilder<Relationship> builder)
    {
        builder.ToTable("relationships");

        builder.HasKey(r => r.Id);

        builder.Property(r => r.Id)
            .HasColumnName("id")
            .ValueGeneratedNever();

        builder.Property<Guid>("_requesterId")
            .HasColumnName("requester_id")
            .IsRequired();

        builder.Property<Guid>("_addresseeId")
            .HasColumnName("addressee_id")
            .IsRequired();

        builder.Property(r => r.TypeId)
            .HasColumnName("type_id")
            .IsRequired();

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

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

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

        // EN: Relationships with enumeration tables
        // VI: Quan hệ với các bảng enumeration
        builder.HasOne(r => r.Type)
            .WithMany()
            .HasForeignKey(r => r.TypeId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(r => r.Status)
            .WithMany()
            .HasForeignKey(r => r.StatusId)
            .OnDelete(DeleteBehavior.Restrict);

        // EN: Unique constraint to prevent duplicate relationships
        // VI: Constraint duy nhất để ngăn quan hệ trùng lặp
        builder.HasIndex("_requesterId", "_addresseeId", "TypeId")
            .IsUnique()
            .HasDatabaseName("ix_relationships_requester_addressee_type");

        // EN: Indexes for efficient queries
        // VI: Indexes cho truy vấn hiệu quả
        builder.HasIndex("_requesterId")
            .HasDatabaseName("ix_relationships_requester");

        builder.HasIndex("_addresseeId")
            .HasDatabaseName("ix_relationships_addressee");

        builder.HasIndex("TypeId", "StatusId")
            .HasDatabaseName("ix_relationships_type_status");

        // EN: Ignore navigation properties for DDD encapsulation
        // VI: Ignore navigation properties cho đóng gói DDD
        builder.Ignore(r => r.DomainEvents);
    }
}
