using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Nuuru.Server.Models; namespace Nuuru.Server.Data { public static class AnonymousUserSeeder { public static async Task EnsureAnonymousUserAsync(IServiceProvider services) { var context = services.GetRequiredService(); var userManager = services.GetRequiredService>(); var logger = services.GetRequiredService>(); // Check if any system account already exists var existingSystemAccount = await context.Users .AnyAsync(u => u.IsSystemAccount); if (existingSystemAccount) { logger.LogInformation("Anonymous system account already exists"); return; } // Check if a user named "Chud" already exists (e.g. from Shimmie migration) var existingChud = await userManager.FindByNameAsync("Chud"); if (existingChud != null) { existingChud.IsSystemAccount = true; await context.SaveChangesAsync(); logger.LogInformation("Marked existing 'Chud' user as system account"); return; } // Create the sentinel user var anonUser = new ApplicationUser { UserName = "Chud", IsSystemAccount = true, LockoutEnabled = false, EmailConfirmed = true, Status = string.Empty, Biography = string.Empty, SecurityStamp = Guid.NewGuid().ToString() }; var result = await userManager.CreateAsync(anonUser); if (result.Succeeded) { logger.LogInformation("Created anonymous system account 'Chud'"); } else { logger.LogError("Failed to create anonymous system account: {Errors}", string.Join(", ", result.Errors.Select(e => e.Description))); } } } }