using Lada.Framework.Data.Mappings.DbContexts;
using ladaexpress.vn.Infrastructures.DTO;
using ladaexpress.vn.Infrastructures.Routes;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System.Data;
using WebMarkupMin.AspNetCoreLatest;
using WebMarkupMin.Core;
using WebMarkupMin.NUglify;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using ladaexpress.vn.Infrastructures.Startup;
namespace ladaexpress.vn.Infrastructures.StartupRegisters
{
    public static class GeneralRegister
    {
        public static void RegisterGeneralServices(this IServiceCollection services, IConfiguration Configuration)
        {
            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
            {
                services.AddControllersWithViews()
                        .AddRazorRuntimeCompilation();
            }
            else
            {
                services.AddControllersWithViews();
            }

            // Đăng ký dịch vụ ResponseCompression
            services.AddResponseCompression();

            string connectionString = Configuration.GetConnectionString("LadaConnection");

            services.AddDbContext<LadaDbContext>(options =>
                        options.UseSqlServer(connectionString, b => b.MigrationsAssembly("Ladaer.BackEnd")), ServiceLifetime.Transient);

            // Khai báo Dapper
            services.AddTransient<IDbConnection>((sp) => new SqlConnection(connectionString));

            services.AddWebMarkupMin(options =>
            {
                options.AllowMinificationInDevelopmentEnvironment = true;
                options.AllowCompressionInDevelopmentEnvironment = true;
            })
            .AddHtmlMinification()
            .AddHttpCompression();



        }

        public static void ConfigAndRunApp(this WebApplication app)
        {
            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //app.UseResponseCompression();
            //app.UseWebOptimizer();
            app.UseWebMarkupMin();

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            // Default route first to handle home page
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            // Dynamic routes for specific patterns
            app.MapDynamicControllerRoute<TagRouteTransformer>("tu-khoa/{slug}");
            app.MapDynamicControllerRoute<ProductRouteTransformer>("dich-vu/{slug}");
            app.MapDynamicControllerRoute<JobPostRouteTransformer>("tuyen-dung/{slug}");

            // Catch-all route last
            app.MapDynamicControllerRoute<RouteTransformer>("{slug}");
            app.UseStatusCodePagesWithReExecute("/Status/HandleError/{0}");


            AutoMapperConfig.Init();

            // Run startup tasks
            using (var scope = app.Services.CreateScope())
            {
                var startupTasks = scope.ServiceProvider.GetServices<IStartupTask>();
                foreach (var task in startupTasks)
                {
                    task.ExecuteAsync().GetAwaiter().GetResult();
                }
            }

            app.Run();
        }
    }
}
