using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using PlaylistShared.Data.Entities;

namespace PlaylistShared.Data.Contexts;

public class AppDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<SharedPlaylist> SharedPlaylists => Set<SharedPlaylist>();
    public DbSet<PlaylistTrack> PlaylistTracks => Set<PlaylistTrack>();

    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

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

        builder.Entity<SharedPlaylist>(entity =>
        {
            entity.HasIndex(p => p.ShareSlug).IsUnique();
            entity.OwnsOne(p => p.Permissions, per =>
            {
                per.Property(x => x.View).HasColumnName("PermView");
                per.Property(x => x.Add).HasColumnName("PermAdd");
                per.Property(x => x.Delete).HasColumnName("PermDelete");
            });
        });

        builder.Entity<PlaylistTrack>(entity =>
        {
            entity.HasOne(pt => pt.Playlist)
                .WithMany(p => p.Tracks)
                .HasForeignKey(pt => pt.PlaylistId)
                .OnDelete(DeleteBehavior.Cascade);
        });
    }
}