using System.Linq;
using DiplomovaPrace.Model.Products;
using Havit.Data.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace DiplomovaPrace.Entity
{
	public class DiplomovaPraceDbContext : Havit.Data.EntityFrameworkCore.DbContext
	{
		/// <summary>
		/// Konstruktor.
		/// Pro použití v unit testech, jiné použití nemá.
		/// </summary>
		public DiplomovaPraceDbContext()
		{
			// NOOP
		}

		/// <summary>
		/// Konstruktor.
		/// </summary>
		public DiplomovaPraceDbContext(DbContextOptions options) : base(options)
		{
			// NOOP
		}

		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
#if DEBUG
			optionsBuilder.UseLoggerFactory(LoggerFactory
				.Create(factory => factory
					.AddConsole()
					.AddFilter((categoryName, logLevel) => (logLevel == LogLevel.Information) && (categoryName == DbLoggerCategory.Database.Command.Name))
					.AddFilter((categoryName, logLevel) => (categoryName == DbLoggerCategory.Database.Transaction.Name))
					.AddFilter((categoryName, logLevel) => logLevel >= LogLevel.Warning)
				)
			);
#endif
		}

		/// <inheritdoc />
		protected override void CustomizeModelCreating(ModelBuilder modelBuilder)
		{
			base.CustomizeModelCreating(modelBuilder);

			modelBuilder.RegisterModelFromAssembly(typeof(ProductCategory).Assembly);
			modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);

			foreach (var foreignKey in modelBuilder.Model.GetEntityTypes().SelectMany(i => i.GetForeignKeys()))
			{
				foreignKey.DeleteBehavior = DeleteBehavior.NoAction;
			}
		}
	}
}
