using System.Reflection;
using Core.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Data
{
    public class AppDbContext : DbContext
    {
        public DbSet<EventDefinition> Events { get; set; }
        public DbSet<Student> Students { get; set; }
        public DbSet<Team> Teams { get; set; }
        public DbSet<StudentEventRanking> StudentEventRanking { get; set; }

        public AppDbContext()
        {
        }

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

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }

        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //{
        //    var dbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ChapterOrganizer.db");
        //    optionsBuilder.UseSqlite($"Data Source={dbPath}");
        //}
    }

    public class EventDefinitionConfiguration : IEntityTypeConfiguration<EventDefinition>
    {
        public void Configure(EntityTypeBuilder<EventDefinition> builder)
        {
            builder.HasKey(u => u.Id);

            builder.HasIndex(u => u.Name);
            builder.Property(u => u.Name).HasMaxLength(128);

            //builder.HasMany(u => u.Roles)
            //    .WithOne()
            //    .HasForeignKey(r => r.Id)
            //    .OnDelete(DeleteBehavior.Restrict);
        }
    }

    public class StudentConfiguration : IEntityTypeConfiguration<Student>
    {
        public void Configure(EntityTypeBuilder<Student> builder)
        {
            builder.HasKey(u => u.Id);
            //builder.Property(s => s.Grade);

            builder
                .HasMany(e => e.RankedEvents)
                .WithMany()
                .UsingEntity<StudentEventRanking>()
                .HasOne<EventDefinition>(e => e.EventDefinition);
        }
    }

    public class TeamConfiguration : IEntityTypeConfiguration<Team>
    {
        public void Configure(EntityTypeBuilder<Team> builder)
        {
            builder.HasKey(u => u.Id);

            builder.HasMany(e => e.Students)
                .WithMany(e => e.Teams);

            builder.HasOne(e => e.Captain);

        }
    }
    public class StudentEventRankingConfiguration : IEntityTypeConfiguration<StudentEventRanking>
    {
        public void Configure(EntityTypeBuilder<StudentEventRanking> builder)
        {
            //builder.HasKey(u => u.EventDefinitionId);
            //builder.HasKey(u => u.StudentId);
        }
    }
}
