using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using WhatsAppService.Domain.AggregatesModel.CustomerAggregate;

namespace WhatsAppService.Infrastructure.EntityConfigurations;

/// <summary>
/// EN: EF Core configuration for Customer entity.
/// VI: Cấu hình EF Core cho entity Customer.
/// </summary>
public class CustomerEntityTypeConfiguration : IEntityTypeConfiguration<Customer>
{
    public void Configure(EntityTypeBuilder<Customer> builder)
    {
        builder.ToTable("customers");
        builder.HasKey(e => e.Id);
        builder.Ignore(e => e.DomainEvents);

        builder.Property(e => e.Id).HasColumnName("id").IsRequired();
        builder.Property<Guid>("_shopId").HasColumnName("shop_id").IsRequired();
        builder.Property<string>("_waId").HasColumnName("wa_id").HasMaxLength(20).IsRequired();
        builder.Property<string?>("_name").HasColumnName("name").HasMaxLength(200);
        builder.Property<string?>("_profilePictureUrl").HasColumnName("profile_picture_url").HasMaxLength(500);
        builder.Property<DateTime>("_firstContactedAt").HasColumnName("first_contacted_at").IsRequired();
        builder.Property<DateTime>("_createdAt").HasColumnName("created_at").IsRequired();
        builder.Property<DateTime?>("_updatedAt").HasColumnName("updated_at");

        // EN: Tags stored as JSONB / VI: Tags lưu dưới dạng JSONB
        builder.Property<List<string>>("_tags")
            .HasColumnName("tags")
            .HasColumnType("jsonb")
            .HasDefaultValueSql("'[]'::jsonb");

        // EN: Custom fields stored as JSONB / VI: Custom fields lưu dưới dạng JSONB
        builder.Property<Dictionary<string, string>>("_customFields")
            .HasColumnName("custom_fields")
            .HasColumnType("jsonb")
            .HasDefaultValueSql("'{}'::jsonb");

        // EN: OptInConsent as owned entity / VI: OptInConsent như owned entity
        builder.OwnsOne<OptInConsent>("_consent", consent =>
        {
            consent.Property(c => c.Status).HasColumnName("opt_in_status").HasMaxLength(20).HasDefaultValue("pending");
            consent.Property(c => c.Timestamp).HasColumnName("opt_in_timestamp");
            consent.Property(c => c.Source).HasColumnName("opt_in_source").HasMaxLength(50);
        });

        builder.HasIndex("_shopId", "_waId").IsUnique().HasDatabaseName("idx_customers_shop_waid");
        builder.HasIndex("_shopId").HasDatabaseName("idx_customers_shop");
    }
}
