using Microsoft.EntityFrameworkCore;
using sotd.Pages;

public class DataContext : DbContext
{
    public static DataContext Instance
    {
        get { return new DataContext(); }
    }

    public DbSet<User>? Users { get; set; }
    public DbSet<Song>? Songs { get; set; }
    public DbSet<SongSuggestion>? SongSuggestions { get; set; }
    public DbSet<SuggestionHelper>? SuggestionHelpers { get; set; }
    public DbSet<SmartPlaylistDefinition>? SmartPlaylistDefinitions { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.UseNpgsql($"Host={AppConfiguration.Instance.DatabaseUri}:{AppConfiguration.Instance.DatabasePort};"
                                    + $"Username={AppConfiguration.Instance.DatabaseUser};Password={AppConfiguration.Instance.DatabasePW};"
                                    + $"Database={AppConfiguration.Instance.DatabaseName}");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // configures one-to-many relationship
        modelBuilder.Entity<User>()
                .HasMany(u => u.LikedSongs)
                .WithMany(s => s.LikedBy)
                .UsingEntity(
                    "LikedSongs",
                    r => r.HasOne(typeof(Song)).WithMany().HasForeignKey("SongId").HasPrincipalKey(nameof(Song.SongId)),
                    l => l.HasOne(typeof(User)).WithMany().HasForeignKey("UserId").HasPrincipalKey(nameof(User.UserId)),
                    j => j.HasKey("SongId", "UserId"));   
    }
}