using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ScadaLink.Commons.Entities.Security;
using ScadaLink.Commons.Entities.Sites;

namespace ScadaLink.ConfigurationDatabase.Configurations;

public class LdapGroupMappingConfiguration : IEntityTypeConfiguration<LdapGroupMapping>
{
    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
        builder.HasData(
            new LdapGroupMapping("SCADA-Admins", "Admin") { Id = 1 },
            new LdapGroupMapping("SCADA-Designers", "Design") { Id = 2 },
            new LdapGroupMapping("SCADA-Deploy-All", "Deployment") { Id = 3 },
            new LdapGroupMapping("SCADA-Deploy-SiteA", "Deployment") { Id = 4 });
    }
}

public class SiteScopeRuleConfiguration : IEntityTypeConfiguration<SiteScopeRule>
{
    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();
    }
}
