namespace Adapters.Driven.Persistence.Configurations;

using Domain.Entities;
using Domain.ValueObjects;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public class StudentConfiguration : IEntityTypeConfiguration<Student>
{
    public void Configure(EntityTypeBuilder<Student> builder)
    {
        builder.ToTable("Students");

        builder.HasKey(s => s.Id);

        builder.Property(s => s.Name)
            .IsRequired()
            .HasMaxLength(100);

        // Email value object with proper converter and comparer
        var emailComparer = new ValueComparer<Email>(
            (e1, e2) => e1 != null && e2 != null && e1.Value == e2.Value,
            e => e.Value.GetHashCode(),
            e => Email.Create(e.Value));

        builder.Property(s => s.Email)
            .IsRequired()
            .HasMaxLength(150)
            .HasConversion(
                e => e.Value,
                v => Email.Create(v))
            .Metadata.SetValueComparer(emailComparer);

        // Use raw column name for index to avoid value object issues
        builder.HasIndex("Email").IsUnique();

        builder.HasMany(s => s.Enrollments)
            .WithOne(e => e.Student)
            .HasForeignKey(e => e.StudentId)
            .OnDelete(DeleteBehavior.Cascade);

        builder.Navigation(s => s.Enrollments).AutoInclude(false);
    }
}
