using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Aberwyn.Models;

namespace Aberwyn.Data
{
    public static class IdentityDataInitializer
    {
        public static async Task<IdentityResult> SeedData(IServiceProvider serviceProvider, SetupSettings? setup = null)
        {
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var config = serviceProvider.GetService<IConfiguration>();

            if (setup == null && config != null)
            {
                setup = config.GetSection("SetupSettings").Get<SetupSettings>() ?? new SetupSettings();
            }

            string[] roles = { "Admin", "Chef", "Budget" };

            foreach (var role in roles)
            {
                if (!await roleManager.RoleExistsAsync(role))
                    await roleManager.CreateAsync(new IdentityRole(role));
            }

            var existingUser = await userManager.FindByEmailAsync(setup.AdminEmail);
            if (existingUser == null)
            {
                var user = new ApplicationUser
                {
                    UserName = setup.AdminUsername,
                    Email = setup.AdminEmail,
                    EmailConfirmed = true
                };

                var result = await userManager.CreateAsync(user, setup.AdminPassword);

                if (result.Succeeded)
                    await userManager.AddToRoleAsync(user, "Admin");

                return result;
            }
            else
            {
                var token = await userManager.GeneratePasswordResetTokenAsync(existingUser);
                var result = await userManager.ResetPasswordAsync(existingUser, token, setup.AdminPassword);

                if (result.Succeeded)
                {
                    var rolesForUser = await userManager.GetRolesAsync(existingUser);
                    if (!rolesForUser.Contains("Admin"))
                        await userManager.AddToRoleAsync(existingUser, "Admin");
                }

                return result;
            }
        }

    }
}
