using HanyadikHetVan.Data;
using HanyadikHetVan.Data.Entities;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading.Tasks;

namespace HanyadikHetVan
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
                await context.Database.MigrateAsync();
                var roleMgr = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
                var userManager = scope.ServiceProvider.GetRequiredService<UserManager<User>>();
                var configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>();
                var adminRole = new IdentityRole("admin");

                if (!await context.Roles.AnyAsync())
                {
                    await roleMgr.CreateAsync(adminRole);
                }

                if (!await userManager.Users.AnyAsync())
                {
                    var defaultAdmin = new User
                    {
                        UserName = configuration.GetValue<string>("DefaultAdministrator:UserName"),
                        Email = configuration.GetValue<string>("DefaultAdministrator:Email"),
                        EmailConfirmed = true,

                    };

                    var result = await userManager.CreateAsync(defaultAdmin,
                        configuration.GetValue<string>("DefaultAdministrator:Password"));
                    if (!result.Succeeded)
                    {
                        throw new Exception("Failed to create the default user.");
                    }
                    else
                    {
                        var roleResult = await userManager.AddToRoleAsync(defaultAdmin, "admin");
                        if (!roleResult.Succeeded)
                        {
                            throw new Exception("Failed to create the default user.");
                        }
                    }
                }
            }

            await host.RunAsync();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}
