using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using AdsTrackingService.Domain.AggregatesModel.TrackingPixelAggregate;

namespace AdsTrackingService.Infrastructure.EntityConfigurations;

/// <summary>
/// EN: Entity configuration for PixelEvent entity.
/// VI: Cấu hình entity cho PixelEvent.
/// </summary>
public class PixelEventEntityTypeConfiguration : IEntityTypeConfiguration<PixelEvent>
{
    public void Configure(EntityTypeBuilder<PixelEvent> builder)
    {
        // EN: Table mapping / VI: Ánh xạ bảng
        builder.ToTable("pixel_events", "ads_tracking");

        // EN: Primary key / VI: Khóa chính
        builder.HasKey(e => e.Id);
        builder.Property(e => e.Id)
            .HasColumnName("id")
            .IsRequired();

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

        builder.Property(e => e.AdId)
            .HasColumnName("ad_id")
            .IsRequired();

        builder.Property(e => e.UserId)
            .HasColumnName("user_id")
            .IsRequired();

        builder.Property(e => e.EventType)
            .HasColumnName("event_type")
            .IsRequired();

        builder.Property(e => e.UserAgent)
            .HasColumnName("user_agent")
            .HasMaxLength(500);

        builder.Property(e => e.IpAddress)
            .HasColumnName("ip_address")
            .HasMaxLength(45); // EN: IPv6 max length / VI: Độ dài tối đa IPv6

        builder.Property(e => e.Timestamp)
            .HasColumnName("timestamp")
            .IsRequired();

        // EN: Indexes for time-series queries / VI: Các index cho query time-series
        builder.HasIndex(e => new { e.PixelId, e.Timestamp })
            .HasDatabaseName("ix_pixel_events_pixel_id_timestamp");

        builder.HasIndex(e => new { e.AdId, e.Timestamp })
            .HasDatabaseName("ix_pixel_events_ad_id_timestamp");

        builder.HasIndex(e => new { e.UserId, e.Timestamp })
            .HasDatabaseName("ix_pixel_events_user_id_timestamp");

        builder.HasIndex(e => e.EventType)
            .HasDatabaseName("ix_pixel_events_event_type");

        // EN: Composite index for analytics / VI: Index tổng hợp cho phân tích
        builder.HasIndex(e => new { e.EventType, e.Timestamp })
            .HasDatabaseName("ix_pixel_events_event_type_timestamp");
    }
}
