using DAL;
using HRD.LDAPService.JWT;
using HRD.WebApi;
using HRD.WebApi.DAL.Middleware;
using HRD.WebApi.Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog.Web;
using StaffDBServer.Extends;
using StaffDBServer.SharedExtensions;
using System;

namespace StaffDBServer
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureWebApiExtensionsAtFirst(); //at first

            services.ConfigureRepositoryWrapper(); //add repos
                
            services.AddDbContext<WebApiContext>(options =>
            {
                const int dbTimeoutInMin = 5;
                var cnnStr = WebApiConfig.ConnectionString(EN_ConnectionType.SQLServer);
                options
                .UseSqlServer(cnnStr,
                    opts => opts.CommandTimeout((int)TimeSpan.FromMinutes(dbTimeoutInMin).TotalSeconds));
            });

            services.AddStaffDBRepositories();

            services.ConfigureWebApiExtensionsEnd(); //should come last
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.ApplicationServices.SetupNLogServiceLocator();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.AddCustomExceptionHandling();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors("AllowAllOrigins");

            app.UseDefaultFiles();
            app.UseStaticFiles();
            
            app.UseOpenApi();

            app.UseDALMiddleware();
            app.UseJwtMiddleware();
            app.ConfigureSwagger();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}