using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using IamService.Domain.AggregatesModel.AuditAggregate;

namespace IamService.Infrastructure.EntityConfigurations;

/// <summary>
/// EN: Entity configuration for AuditLog.
/// VI: Cấu hình entity cho AuditLog.
/// </summary>
public class AuditLogEntityConfiguration : IEntityTypeConfiguration<AuditLog>
{
    public void Configure(EntityTypeBuilder<AuditLog> builder)
    {
        builder.ToTable("AuditLogs");
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Id).ValueGeneratedNever();

        builder.Property<Guid?>("_actorId").HasColumnName("ActorId");
        builder.Property<string?>("_actorEmail").HasColumnName("ActorEmail").HasMaxLength(256);
        builder.Property<string>("_resourceType").HasColumnName("ResourceType").HasMaxLength(100).IsRequired();
        builder.Property<Guid?>("_resourceId").HasColumnName("ResourceId");
        builder.Property<string?>("_action").HasColumnName("Action").HasMaxLength(200);
        builder.Property<string?>("_details").HasColumnName("Details").HasMaxLength(4000);
        builder.Property<string?>("_ipAddress").HasColumnName("IpAddress").HasMaxLength(45);
        builder.Property<string?>("_userAgent").HasColumnName("UserAgent").HasMaxLength(500);
        builder.Property<bool>("_success").HasColumnName("Success");
        builder.Property<DateTime>("_timestamp").HasColumnName("Timestamp").IsRequired();

        builder.Property<AuditEventType>("_eventType")
            .HasColumnName("EventTypeId")
            .HasConversion(v => v.Id, v => AuditEventType.FromId(v) ?? AuditEventType.Login);

        builder.Ignore(x => x.DomainEvents);

        // Indexes for common queries
        builder.HasIndex("_timestamp").HasDatabaseName("IX_AuditLogs_Timestamp");
        builder.HasIndex("_actorId").HasDatabaseName("IX_AuditLogs_ActorId");
        builder.HasIndex("_eventType").HasDatabaseName("IX_AuditLogs_EventType");
        builder.HasIndex("_resourceType", "_resourceId").HasDatabaseName("IX_AuditLogs_Resource");
    }
}
