using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Security;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;

namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Configurations;

public class LdapGroupMappingConfiguration : IEntityTypeConfiguration<LdapGroupMapping>
{
    /// <summary>
    /// Configures the EF Core entity type mapping for <see cref="LdapGroupMapping"/>.
    /// </summary>
    /// <param name="builder">The entity type builder to configure.</param>
    public void Configure(EntityTypeBuilder<LdapGroupMapping> builder)
    {
        builder.HasKey(m => m.Id);

        builder.Property(m => m.LdapGroupName)
            .IsRequired()
            .HasMaxLength(500);

        builder.Property(m => m.Role)
            .IsRequired()
            .HasMaxLength(100);

        builder.HasIndex(m => m.LdapGroupName).IsUnique();

        // Seed default group mappings matching GLAuth test users.
        // Role VALUES are the canonical six: Administrator/Designer/
        // Deployer. The LDAP group NAMES (SCADA-Admins etc.) are unchanged —
        // only the role each group maps to was canonicalized.
        builder.HasData(
            new LdapGroupMapping("SCADA-Admins", "Administrator") { Id = 1 },
            new LdapGroupMapping("SCADA-Designers", "Designer") { Id = 2 },
            new LdapGroupMapping("SCADA-Deploy-All", "Deployer") { Id = 3 },
            new LdapGroupMapping("SCADA-Deploy-SiteA", "Deployer") { Id = 4 },
            // SCADA-Viewers → Viewer completes the four-role set so the GLAuth
            // "multi-role" test user (a member of every SCADA-* group) resolves to
            // Administrator + Designer + Deployer + Viewer.
            new LdapGroupMapping("SCADA-Viewers", "Viewer") { Id = 5 });
    }
}

public class SiteScopeRuleConfiguration : IEntityTypeConfiguration<SiteScopeRule>
{
    /// <summary>
    /// Configures the EF Core entity type mapping for <see cref="SiteScopeRule"/>.
    /// </summary>
    /// <param name="builder">The entity type builder to configure.</param>
    public void Configure(EntityTypeBuilder<SiteScopeRule> builder)
    {
        builder.HasKey(r => r.Id);

        builder.HasOne<LdapGroupMapping>()
            .WithMany()
            .HasForeignKey(r => r.LdapGroupMappingId)
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasOne<Site>()
            .WithMany()
            .HasForeignKey(r => r.SiteId)
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasIndex(r => new { r.LdapGroupMappingId, r.SiteId }).IsUnique();
    }
}
