using Microsoft.AspNetCore.Identity;

namespace Integrations.Data.Seeders;

public static class AdminSeeder
{
	private const string Password = "qweQWE123!@#";
	private const string AdminRoleName = "Admin";
	private const string AdminUsername = "admin";
	private const string AdminEmail = "admin@admin.com";

	public static async Task Seed(IServiceProvider serviceProvider)
	{
		using var scope = serviceProvider.CreateScope();
		var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
		var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();

		// Добавляем роль администратора, если её ещё нет
		if (!await roleManager.RoleExistsAsync(AdminRoleName))
			await roleManager.CreateAsync(new IdentityRole(AdminRoleName));

		// Проверяем, есть ли уже админ
		var admin = await userManager.FindByNameAsync(AdminUsername);
		if (admin == null)
		{
			admin = new ApplicationUser
			{
				UserName = AdminUsername,
				Email = AdminEmail,
				EmailConfirmed = true
			};

			await userManager.CreateAsync(admin, Password); // пароль в чистом виде
			await userManager.AddToRoleAsync(admin, AdminRoleName);
		}
	}
}
