using Core.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Data.Configurations
{
    public class TeamConfiguration : IEntityTypeConfiguration<Team>
    {
        public void Configure(EntityTypeBuilder<Team> builder)
        {
            builder.HasKey(t => t.Id);

            // Indexes on shadow properties created by EF Core
            builder.HasIndex("EventId");
            builder.HasIndex("EventId", "Identifier");

            // Constraints
            builder.Property(t => t.Identifier)
                .HasMaxLength(50);

            // Relationships
            builder.HasOne(t => t.Event)
                .WithMany()
                .IsRequired()
                .OnDelete(DeleteBehavior.Restrict); // Don't delete teams when event is deleted

            builder.HasMany(t => t.Students)
                .WithMany(s => s.Teams)
                .UsingEntity(j => j.ToTable("TeamStudents")); // Explicit table name

            builder.HasOne(t => t.Captain)
                .WithMany()
                .IsRequired(false)
                .OnDelete(DeleteBehavior.SetNull); // Set to null if captain is deleted
        }
    }
}
