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

public class WardGatewayConfiguration : IEntityTypeConfiguration<WardGateway>
{
    public void Configure(EntityTypeBuilder<WardGateway> builder)
    {
        builder.ToTable("ward_gateways", t =>
        {
            t.HasCheckConstraint("chk_ward_gateways_status",
                "status IN ('ONLINE','DEGRADED','OFFLINE')");
        });
        builder.HasKey(g => g.Id);
        builder.Property(g => g.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(g => g.SiteId).HasColumnName("site_id");
        builder.Property(g => g.GatewayCode).HasColumnName("gateway_code").HasMaxLength(64).IsRequired();
        builder.Property(g => g.Department).HasColumnName("department").HasMaxLength(100).IsRequired();
        builder.Property(g => g.Status)
            .HasColumnName("status")
            .HasMaxLength(16)
            .HasConversion(v => v.ToDbString(), v => GatewayStatusExtensions.FromDbString(v))
            .HasDefaultValueSql("'OFFLINE'")
            .HasSentinel((GatewayStatus)(-1));
        builder.Property(g => g.ReportedBufferDepth).HasColumnName("reported_buffer_depth").HasDefaultValue(0);
        builder.Property(g => g.LastHeartbeatAt).HasColumnName("last_heartbeat_at");
        builder.Property(g => g.LastSyncAt).HasColumnName("last_sync_at");
        builder.Property(g => g.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");

        builder.HasOne(g => g.Site)
            .WithMany(s => s.Gateways)
            .HasForeignKey(g => g.SiteId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(g => new { g.SiteId, g.GatewayCode }).IsUnique();
        builder.HasIndex(g => new { g.SiteId, g.Department });
        builder.HasIndex(g => g.Status).HasFilter("status != 'ONLINE'");
    }
}
