using API.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace API.Services
{
    public class IdentitySeedService(
        UserManager<AppUser> userManager,
        IConfiguration configuration,
        ILogger<IdentitySeedService> logger)
    {
        public async Task SeedAsync()
        {
            var hasAdmin = await userManager.Users.AnyAsync(x => x.IsAdmin);

            if (hasAdmin)
            {
                logger.LogDebug("Admin-Seed übersprungen: Es existiert bereits ein Admin-Account.");
                return;
            }

            var adminUserName = configuration["SeedAdmin:UserName"] ?? "admin";
            var adminPassword = configuration["SeedAdmin:Password"] ?? "HoardPassword";
            var adminEmail = configuration["SeedAdmin:Email"];

            var admin = new AppUser
            {
                UserName = adminUserName,
                Email = string.IsNullOrWhiteSpace(adminEmail) ? null : adminEmail,
                IsAdmin = true,
                IsActive = true,
                MustChangePassword = true,
                CreatedAt = DateTimeOffset.UtcNow,
                UpdatedAt = DateTimeOffset.UtcNow
            };

            var result = await userManager.CreateAsync(admin, adminPassword);

            if (!result.Succeeded)
            {
                var errors = string.Join(", ", result.Errors.Select(x => x.Description));
                logger.LogError("Admin-Seed fehlgeschlagen: {Errors}", errors);
                throw new InvalidOperationException($"Admin-Seed fehlgeschlagen: {errors}");
            }

            logger.LogInformation(
                "Admin-Account wurde geseedet (UserName: {UserName}, Email: {Email}).",
                admin.UserName,
                admin.Email ?? "(keine)");
        }
    }
}
