namespace DocuMed.Repository.Services;

public class DbInitializerService(
    ApplicationContext context,
    RoleManager<ApplicationRole> roleManager,
    UserManager<ApplicationUser> userManager,
    IOptionsSnapshot<SiteSettings> adminUserSeedOptions,
    ILogger<DbInitializerService> logger)
    : IDbInitializerService
{
    public void Initialize()
    {
        try
        {
            context.Database.Migrate();
            logger.LogInformation("Migration SUCCESS !!!!");
        }
        catch (Exception e)
        {
            logger.LogError(e, e.Message);
        }
    }

    public async Task SeedDate(bool force = false)
    {
        try
        {
            await SeedRoles();

            var seedAdmin = adminUserSeedOptions.Value.UserSetting;
            var user = await userManager.FindByNameAsync(seedAdmin.Username);
            if (user == null)
            {
                var adminUser = new ApplicationUser
                {
                    UserName = seedAdmin.Username,
                    Email = seedAdmin.Email,
                    EmailConfirmed = true,
                    LockoutEnabled = true,
                    FirstName = seedAdmin.FirstName,
                    LastName = seedAdmin.LastName,
                    Gender = Gender.Male,
                    PhoneNumberConfirmed = true,
                    PhoneNumber = seedAdmin.Phone,
                    BirthDate = DateTime.Now.AddYears(-23)
                };
                var adminUserResult = await userManager.CreateAsync(adminUser, seedAdmin.Password);
                if (adminUserResult.Succeeded) await userManager.AddToRoleAsync(adminUser, seedAdmin.RoleName);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    public async Task SeedRoles()
    {
        var seedAdmin = adminUserSeedOptions.Value.UserSetting;
        var managerRole = await roleManager.FindByNameAsync(seedAdmin.RoleName);

        if (managerRole == null)
        {
            managerRole = new ApplicationRole
            {
                Name = seedAdmin.RoleName,
                EnglishName = seedAdmin.RoleName,
                Description = "root admin role"
            };
            var adminRoleResult = await roleManager.CreateAsync(managerRole);
            foreach (var claim in ApplicationClaims.AllClaims)
                await roleManager.AddClaimAsync(managerRole, claim);
        }
    }
}