using HanyadikHetVan.Data;
using HanyadikHetVan.Data.Entities;
using HanyadikHetVan.Infrastructure;
using HanyadikHetVan.Services;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection;

namespace HanyadikHetVan
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseNpgsql(
                    Configuration.GetConnectionString("PostgreSQLConnection")));
            services.AddAutoMapper(Assembly.GetExecutingAssembly());
            services.AddTransient<WeeklyTimeSpanService>();
            services.AddTransient<PauseService>();
            services.AddTransient<UserService>();
            services.AddTransient<FunFactService>();
            services.AddTransient<HanyadikHetVanEntityService>();
            services.AddTransient<HanyadikHetVanJsonService>();
            services.AddTransient<IdentityService>();
            services.AddTransient<HanyadikHetVanService>();
            services.AddTransient<IProfileService, ProfileService>();
            services.AddTransient<IEmailSender, EmailSender>();
            services.Configure<EmailSenderConfig>(Configuration.GetSection("EmailSender"));
            services.AddDatabaseDeveloperPageExceptionFilter();
            services.AddHealthChecks().AddDbContextCheck<ApplicationDbContext>();

            services.AddAuthentication(config =>
                {
                    config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(config =>
                {
                    config.Authority = "https://localhost:5001";
                    config.Audience = "api";
                    config.RequireHttpsMetadata = false;
                    config.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = false,
                        ValidateAudience = true,
                        ValidateIssuerSigningKey = false,
                        RequireSignedTokens = false,
                        SignatureValidator = delegate (string token, TokenValidationParameters parameters)
                        {
                            return new JwtSecurityToken(token);
                        },
                        ValidateLifetime = false,
                        RequireExpirationTime = false
                    };
                });

            services.AddAuthorization(config =>
            {
                config.AddPolicy("default", config => config.RequireAuthenticatedUser().AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme));
                config.DefaultPolicy = config.GetPolicy("default");
                config.AddPolicy("AdminPolicy", p => p.RequireClaim("user_role", "admin"));
            });

            services.AddIdentity<User, IdentityRole>(options => { options.SignIn.RequireConfirmedAccount = true; })
                .AddDefaultTokenProviders()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer(o =>
            {
                o.UserInteraction.LoginUrl = "/Identity/Account/Login";
                o.UserInteraction.LogoutUrl = "/Identity/Account/Logout";
                o.UserInteraction.ErrorUrl = "/Identity/Account/Error";
            })
                .AddDeveloperSigningCredential()
                .AddInMemoryPersistedGrants()
                .AddInMemoryIdentityResources(Configuration.GetSection("IdentityServer:IdentityResources"))
                .AddInMemoryApiResources(Configuration.GetSection("IdentityServer:ApiResources"))
                .AddInMemoryApiScopes(Configuration.GetSection("IdentityServer:ApiScopes"))
                .AddInMemoryClients(Configuration.GetSection("IdentityServer:Clients"))
                .AddAspNetIdentity<User>()
                .AddProfileService<ProfileService>();

            services.AddRazorPages();

            services.AddControllers();

            services.AddApiVersioning(options =>
            {
                options.ReportApiVersions = true;
            });

            services.AddVersionedApiExplorer(options =>
            {
                options.GroupNameFormat = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            });

            services.AddSwaggerGen(c =>
            {
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        AuthorizationCode = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri("https://localhost:5001/connect/authorize"),
                            TokenUrl = new Uri("https://localhost:5001/connect/token"),
                            Scopes = new Dictionary<string, string>
                            {
                                {"profile", "Profile"},
                                {"openid", "OpenID"},
                                {"user_role", "User roles"},
                                {"api.readwrite", "Access to api"}
                            }
                        }
                    }
                });
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Hanyadik Het Van API", Version = "v1" });
                c.SwaggerDoc("v2", new OpenApiInfo { Title = "Hanyadik Het Van API", Version = "v2" });
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("v1/swagger.json", "Original API");
                    c.SwaggerEndpoint("v2/swagger.json", "Homework API");
                });
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseIdentityServer();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHealthChecks("/healthz");
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });
        }
    }
}
