﻿namespace MyCompany.MyProject.EntityFrameworkCore.Seed.Tenants
{
    using Microsoft.EntityFrameworkCore;
    using System.Linq;

    /// <summary>
    /// Represents the default tenant builder to create the default tenants in the database.
    /// </summary>
    public class DefaultTenantBuilder
    {
        #region Fields

        private readonly MyProjectDbContext _context;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultTenantBuilder"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        public DefaultTenantBuilder(MyProjectDbContext context)
        {
            _context = context;
        }

        #endregion Constructors

        #region Methods

        /// <summary>
        /// Creates the default tenant.
        /// </summary>
        public void Create()
        {
            CreateDefaultTenant();
        }

        /// <summary>
        /// Creates the default tenant.
        /// </summary>
        private void CreateDefaultTenant()
        {
            // Default tenant
            Core.MultiTenancy.Tenant defaultTenant = _context
                .Tenants
                .IgnoreQueryFilters()
                .FirstOrDefault(t => t.TenancyName == Core.MultiTenancy.Tenant.DefaultTenantName);
            if (defaultTenant == null)
            {
                defaultTenant = new Core.MultiTenancy.Tenant(Core.MultiTenancy.Tenant.DefaultTenantName, Core.MultiTenancy.Tenant.DefaultTenantName);

                Dike.Core.Application.Editions.Edition defaultEdition = _context
                    .Editions
                    .IgnoreQueryFilters()
                    .FirstOrDefault(e => e.Name == Core.Editions.EditionManager.DefaultEditionName);
                if (defaultEdition != null)
                {
                    defaultTenant.EditionId = defaultEdition.Id;
                }

                _context.Tenants.Add(defaultTenant);
                _context.SaveChanges();
            }
        }

        #endregion Methods
    }
}