using Microsoft.EntityFrameworkCore;

namespace Harmonia.Core.Library;

public class AudioLibraryContext(DbContextOptions options) : DbContext(options)
{
    public DbSet<Location> Locations { get; set; }
    public DbSet<Folder> Folders { get; set; }
    public DbSet<Song> Songs { get; set; }
    public DbSet<SongTag> SongTags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        ConfigureLocation(modelBuilder);
        ConfigureFolder(modelBuilder);
        ConfigureSong(modelBuilder);
        ConfigureSongTag(modelBuilder);
    }

    private static void ConfigureLocation(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Location>()
            .HasKey(x => x.LocationId);

        modelBuilder
            .Entity<Location>()
            .HasMany(x => x.Folders)
            .WithOne(x => x.Location)
        .OnDelete(DeleteBehavior.ClientCascade);
    }

    private static void ConfigureFolder(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Folder>()
            .HasKey(x => x.FolderId);

        modelBuilder
            .Entity<Folder>()
            //.HasIndex(x => new { x.LocationId, x.Name })
            .HasIndex(x => new { x.Name })
            .IsUnique(true);

        modelBuilder
            .Entity<Folder>()
            .HasMany(x => x.Songs)
            .WithOne(x => x.Folder)
        .OnDelete(DeleteBehavior.ClientCascade);
    }

    private static void ConfigureSong(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Song>()
        .HasKey(x => x.SongId);

        modelBuilder
            .Entity<Song>()
            .HasIndex(x => new { x.FolderId, x.FileName })
            .IsUnique(true);

        modelBuilder.Entity<Song>()
            .HasOne(x => x.SongTag)
            .WithOne(x => x.Song)
        .OnDelete(DeleteBehavior.ClientCascade);
    }

    private static void ConfigureSongTag(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<SongTag>()
            .HasKey(x => x.SongTagId);

        modelBuilder
            .Entity<SongTag>()
            .HasIndex(x => x.SongId)
            .IsUnique(true);

        modelBuilder
            .Entity<SongTag>()
            .HasIndex(x => x.Album);

        modelBuilder
            .Entity<SongTag>()
            .HasIndex(x => x.Title);

        modelBuilder
            .Entity<SongTag>()
            .HasIndex(x => x.Artist);

        modelBuilder
            .Entity<SongTag>()
            .HasIndex(x => x.AlbumArtist);

        modelBuilder
            .Entity<SongTag>()
            .HasIndex(x => x.DiscNumber);

        modelBuilder
            .Entity<SongTag>()
            .HasIndex(x => x.TrackNumber);

        modelBuilder
            .Entity<SongTag>()
            .HasIndex(x => x.Genre);

        modelBuilder
            .Entity<SongTag>()
            .HasIndex(x => x.ReleaseDate);
    }
}