using Infrastructure.Persistence.Identity;
using Microsoft.AspNetCore.Identity;

namespace Admin.Extensions
{
    public static class WebApplicationExtensions
    {
        /// <summary>
        /// 초기 관리자 계정 및 Admin 역할을 시드합니다.
        /// 계정이 이미 존재하면 Admin 역할만 보장합니다.
        /// </summary>
        public static async Task SeedAdminAccountAsync(this WebApplication app)
        {
            using var scope = app.Services.CreateScope();

            var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();

            const string adminEmail = "jino@dpot.dev";
            const string adminPassword = "Admin@1234";
            const string adminRoleName = "Admin";

            // Admin 역할이 없으면 생성
            if (!await roleManager.RoleExistsAsync(adminRoleName))
            {
                await roleManager.CreateAsync(new IdentityRole(adminRoleName));
            }

            // 관리자 계정이 없으면 생성
            var existingUser = await userManager.FindByEmailAsync(adminEmail);
            if (existingUser == null)
            {
                var adminUser = new ApplicationUser
                {
                    UserName = adminEmail,
                    Email = adminEmail,
                    EmailConfirmed = true
                };

                var result = await userManager.CreateAsync(adminUser, adminPassword);
                if (result.Succeeded)
                {
                    await userManager.AddToRoleAsync(adminUser, adminRoleName);
                    Console.WriteLine($"[Seed] 관리자 계정 생성 완료: {adminEmail}");
                }
                else
                {
                    Console.WriteLine($"[Seed] 관리자 계정 생성 실패: {string.Join(", ", result.Errors.Select(e => e.Description))}");
                }
            }
            else
            {
                // 기존 계정이 Admin 역할이 없으면 추가
                if (!await userManager.IsInRoleAsync(existingUser, adminRoleName))
                {
                    await userManager.AddToRoleAsync(existingUser, adminRoleName);
                    Console.WriteLine($"[Seed] 기존 계정에 Admin 역할 부여: {adminEmail}");
                }
            }
        }
    }
}