using Data.Data.Configurations;
using DeepDrftModels.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace DeepDrftData.Data.Configurations;

public class TrackConfiguration : BaseEntityConfiguration<TrackEntity>
{
    public override void Configure(EntityTypeBuilder<TrackEntity> builder)
    {
        // Wires up Id PK + audit columns (CreatedAt, UpdatedAt, IsDeleted) and the IsDeleted index.
        base.Configure(builder);

        builder.ToTable("track");

        // Map the base audit columns to the snake_case naming the rest of the schema uses.
        builder.Property(e => e.Id).HasColumnName("id");
        builder.Property(e => e.CreatedAt).HasColumnName("created_at");
        builder.Property(e => e.UpdatedAt).HasColumnName("updated_at");
        builder.Property(e => e.IsDeleted).HasColumnName("is_deleted");

        builder.Property(e => e.EntryKey)
            .IsRequired()
            .HasMaxLength(100)
            .HasColumnName("entry_key");

        builder.Property(e => e.TrackName)
            .IsRequired()
            .HasMaxLength(200)
            .HasColumnName("track_name");

        builder.Property(e => e.OriginalFileName)
            .HasMaxLength(500)
            .HasColumnName("original_file_name");

        builder.Property(e => e.TrackNumber)
            .IsRequired()
            .HasColumnName("track_number")
            .HasDefaultValue(1);

        // Nullable: existing rows carry NULL until the one-time duration backfill populates them.
        builder.Property(e => e.DurationSeconds)
            .HasColumnName("duration_seconds");

        builder.Property(e => e.ReleaseId)
            .HasColumnName("release_id");

        // Nullable FK to the release-cardinal row. SetNull on delete: removing a release leaves its
        // tracks intact as loose tracks rather than cascading them away.
        builder.HasOne(e => e.Release)
            .WithMany(r => r.Tracks)
            .HasForeignKey(e => e.ReleaseId)
            .OnDelete(DeleteBehavior.SetNull);

        // Names the is_deleted index explicitly. BaseEntityConfiguration.Configure already
        // calls HasIndex(e => e.IsDeleted); this adds HasDatabaseName so EF always uses
        // "IX_track_is_deleted" regardless of auto-naming conventions.
        builder.HasIndex(e => e.IsDeleted).HasDatabaseName("IX_track_is_deleted");
    }
}
