using DAL;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using StaffDBServer.Controllers;
using StaffDBServer.SharedControllers;

namespace XUnitWebApi.Test
{
    public class TestBuilder
    {
        private readonly ServiceCollection _services = new();

        public ServiceCollection Services => !_lazyProvider.IsValueCreated 
            ? _services 
            : throw new InvalidOperationException("Service provider has already been created.");

        private readonly Lazy<IServiceProvider> _lazyProvider;

        public IServiceProvider Provider => _lazyProvider.Value;

        public TestBuilder() 
        {
            Services.AddStaffDBRepositories();
            Services.AddScoped<WebAppUserHelper>();
            Services.AddDbContext<WebApiContext>(options =>
            {
                const int dbTimeoutInMin = 5;
                options.UseSqlServer(
                    "Server=SDD-VMP04-SQL17\\DD_DEVELOP01;Database=DD_ECM;User Id=sa;Password=dd;Encrypt=false;TrustServerCertificate=True;",
                    opts => opts.CommandTimeout((int)TimeSpan.FromMinutes(dbTimeoutInMin).TotalSeconds));
            });
            Services.AddSingleton<SubsidiaryController>();

            _lazyProvider = new(Services.BuildServiceProvider);
        }

        public void ForceBuild() => _ = Provider;
    }
}