using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public class AuthAuditEventConfiguration : IEntityTypeConfiguration<AuthAuditEvent>
{
    public void Configure(EntityTypeBuilder<AuthAuditEvent> builder)
    {
        builder.ToTable("auth_audit_events", t =>
        {
            t.HasCheckConstraint("chk_auth_audit_events_event_type",
                "event_type IN ('USER_LOGOUT', 'TOKEN_REFRESHED')");
        });
        builder.HasKey(e => e.Id);
        builder.Property(e => e.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(e => e.UserId).HasColumnName("user_id").IsRequired();
        builder.Property(e => e.EventType)
            .HasColumnName("event_type")
            .HasMaxLength(30)
            .HasConversion(
                v => v.ToDbString(),
                v => AuthAuditEventTypeExtensions.FromDbString(v))
            .IsRequired();
        builder.Property(e => e.OccurredAt).HasColumnName("occurred_at").HasDefaultValueSql("NOW()");
        builder.Property(e => e.MetadataJson).HasColumnName("metadata_json").HasColumnType("jsonb");

        builder.HasOne(e => e.User).WithMany().HasForeignKey(e => e.UserId).OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(e => new { e.UserId, e.OccurredAt });
    }
}
