using Expedience.Infrastructure.Models;
using Expedience.Models;
using Microsoft.EntityFrameworkCore;

namespace Expedience.Infrastructure
{
    public class ExpedienceContext : DbContext
    {
        public ExpedienceContext(DbContextOptions<ExpedienceContext> dbContextOptions) : base(dbContextOptions)
        {
        }

        public DbSet<DutyCompletionResult> DutyCompletionResults { get; set; }

        public DbSet<DutyMember> DutyMembers { get; set; }

        public DbSet<Territory> Territories { get; set; }

        public DbSet<User> Users { get; set; }
        public DbSet<DutyCompletionRecord> DutyCompletionRecords { get; set; }
        public DbSet<DeepDungeonRecord> DeepDungeonRecords { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<DutyCompletionResult>(cfg =>
            {
                cfg.ToTable("dutycompletionresult");
                cfg.HasKey(e => e.Id);

                cfg.HasOne(e => e.Territory)
                    .WithMany(e => e.DutyCompletionResults)
                    .HasForeignKey(e => e.TerritoryId);

                cfg.HasOne(e => e.User)
                    .WithMany(e => e.DutyCompletionResults)
                    .HasForeignKey(e => e.UserId);

            });

            modelBuilder.Entity<DutyMember>(cfg =>
            {
                cfg.ToTable("dutymember");

                cfg.HasKey(e => new { e.UploadId, e.GroupNumber, e.MemberNumber });

                cfg.HasOne(o => o.DutyCompletionResult)
                   .WithMany(o => o.DutyMembers)
                   .HasForeignKey(o => o.UploadId);
            });

            modelBuilder.Entity<User>(cfg =>
            {
                cfg.ToTable("user");

                cfg.Property(e => e.UserId)
                    .UseIdentityAlwaysColumn()
                    .IsRequired()
                    .ValueGeneratedOnAdd();

                cfg.HasKey(e => new { e.UserId });
                cfg.HasIndex(e => new { e.WorldId, e.UserName });
                cfg.HasIndex(e => new { e.WorldId, e.UserHash });
            });

            modelBuilder.Entity<Territory>(cfg =>
            {
                cfg.ToTable("territory");
                cfg.HasKey(e => new { e.TerritoryId });
            });

            modelBuilder.Entity<DutyCompletionRecord>()
                .HasNoKey()
                .ToTable(t => t.ExcludeFromMigrations());

            modelBuilder.Entity<DeepDungeonRecord>()
                .HasNoKey()
                .ToTable(t => t.ExcludeFromMigrations());

            base.OnModelCreating(modelBuilder);
        }
    }
}
