using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using UniVerse.Domain.Entities;

namespace UniVerse.Infrastructure.Data.Configurations;

public class LectureConfiguration : IEntityTypeConfiguration<Lecture>
{
    public void Configure(EntityTypeBuilder<Lecture> builder)
    {
        builder.ToTable("lectures");

        builder.HasKey(l => l.Id);
        builder.Property(l => l.Id).HasColumnName("id");
        builder.Property(l => l.CourseId).HasColumnName("course_id");
        builder.Property(l => l.TeacherId).HasColumnName("teacher_id");
        builder.Property(l => l.LocationId).HasColumnName("location_id");
        builder.Property(l => l.Title).HasColumnName("title").HasMaxLength(500).IsRequired();
        builder.Property(l => l.Description).HasColumnName("description");
        builder.Property(l => l.Format).HasColumnName("format");
        builder.Property(l => l.StartsAt).HasColumnName("starts_at");
        builder.Property(l => l.EndsAt).HasColumnName("ends_at");
        builder.Property(l => l.IsOpen).HasColumnName("is_open").HasDefaultValue(true);
        builder.Property(l => l.MaxEnrollments).HasColumnName("max_enrollments").HasDefaultValue(0);
        builder.Property(l => l.MandatoryAttendeesCount).HasColumnName("mandatory_attendees_count").HasDefaultValue(0);
        builder.Property(l => l.ExternalId).HasColumnName("external_id").HasMaxLength(255);
        builder.Property(l => l.OnlineUrl).HasColumnName("online_url").HasMaxLength(500);
        builder.Property(l => l.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");
        builder.Property(l => l.UpdatedAt).HasColumnName("updated_at").HasDefaultValueSql("NOW()");

        builder.HasOne(l => l.Course)
            .WithMany(c => c.Lectures)
            .HasForeignKey(l => l.CourseId)
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasOne(l => l.Teacher)
            .WithMany()
            .HasForeignKey(l => l.TeacherId)
            .OnDelete(DeleteBehavior.SetNull);

        builder.HasOne(l => l.Location)
            .WithMany(loc => loc.Lectures)
            .HasForeignKey(l => l.LocationId)
            .OnDelete(DeleteBehavior.SetNull);

        builder.HasIndex(l => l.ExternalId).IsUnique().HasFilter("external_id IS NOT NULL");
        builder.HasIndex(l => l.StartsAt);
        builder.HasIndex(l => l.CourseId);
    }
}
