using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using MktXService.Domain.AggregatesModel.SegmentAggregate;

namespace MktXService.Infrastructure.EntityConfigurations;

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

        builder.HasKey(s => s.Id);
        builder.Ignore(s => s.DomainEvents);

        builder.Property(s => s.Id)
            .HasColumnName("id")
            .IsRequired();

        builder.Property<Guid>("_merchantId")
            .HasColumnName("merchant_id")
            .IsRequired();

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

        builder.Property<int>("_contactCount")
            .HasColumnName("contact_count")
            .HasDefaultValue(0);

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

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

        // EN: One-to-many with SegmentConditions
        builder.HasMany(s => s.Conditions)
            .WithOne()
            .HasForeignKey(c => c.SegmentId)
            .OnDelete(DeleteBehavior.Cascade);

        // EN: Indexes
        builder.HasIndex("_merchantId")
            .HasDatabaseName("ix_segments_merchant_id");

        builder.HasIndex("_name")
            .HasDatabaseName("ix_segments_name");
    }
}

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

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

        builder.Property(c => c.Id)
            .HasColumnName("id")
            .IsRequired();

        builder.Property(c => c.SegmentId)
            .HasColumnName("segment_id")
            .IsRequired();

        builder.Property<string>("_field")
            .HasColumnName("field")
            .HasMaxLength(100)
            .IsRequired();

        builder.Property<string>("_operator")
            .HasColumnName("operator")
            .HasMaxLength(50)
            .IsRequired();

        builder.Property<string>("_value")
            .HasColumnName("value")
            .HasMaxLength(500);

        builder.HasIndex(c => c.SegmentId)
            .HasDatabaseName("ix_segment_conditions_segment_id");
    }
}
