| | | 1 | | using Chronicis.Api.Data; |
| | | 2 | | using Chronicis.Shared.DTOs; |
| | | 3 | | using Chronicis.Shared.Enums; |
| | | 4 | | using Chronicis.Shared.Extensions; |
| | | 5 | | using Chronicis.Shared.Models; |
| | | 6 | | using Chronicis.Shared.Utilities; |
| | | 7 | | using Microsoft.EntityFrameworkCore; |
| | | 8 | | |
| | | 9 | | namespace Chronicis.Api.Services; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Service for core world management (CRUD, lookup, creation) |
| | | 13 | | /// </summary> |
| | | 14 | | public class WorldService : IWorldService |
| | | 15 | | { |
| | | 16 | | private readonly ChronicisDbContext _context; |
| | | 17 | | private readonly IWorldMembershipService _membershipService; |
| | | 18 | | private readonly IWorldPublicSharingService _publicSharingService; |
| | | 19 | | private readonly ILogger<WorldService> _logger; |
| | | 20 | | |
| | 17 | 21 | | public WorldService( |
| | 17 | 22 | | ChronicisDbContext context, |
| | 17 | 23 | | IWorldMembershipService membershipService, |
| | 17 | 24 | | IWorldPublicSharingService publicSharingService, |
| | 17 | 25 | | ILogger<WorldService> logger) |
| | | 26 | | { |
| | 17 | 27 | | _context = context; |
| | 17 | 28 | | _membershipService = membershipService; |
| | 17 | 29 | | _publicSharingService = publicSharingService; |
| | 17 | 30 | | _logger = logger; |
| | 17 | 31 | | } |
| | | 32 | | |
| | | 33 | | public async Task<List<WorldDto>> GetUserWorldsAsync(Guid userId) |
| | | 34 | | { |
| | 3 | 35 | | var worlds = await _context.Worlds |
| | 3 | 36 | | .Where(w => w.Members.Any(m => m.UserId == userId)) |
| | 3 | 37 | | .Include(w => w.Owner) |
| | 3 | 38 | | .Include(w => w.Campaigns) |
| | 3 | 39 | | .Include(w => w.Members) |
| | 3 | 40 | | .ToListAsync(); |
| | | 41 | | |
| | 3 | 42 | | return worlds.Select(MapToDto).ToList(); |
| | 3 | 43 | | } |
| | | 44 | | |
| | | 45 | | public async Task<WorldDetailDto?> GetWorldAsync(Guid worldId, Guid userId) |
| | | 46 | | { |
| | 3 | 47 | | var world = await _context.Worlds |
| | 3 | 48 | | .Include(w => w.Owner) |
| | 3 | 49 | | .Include(w => w.Campaigns) |
| | 3 | 50 | | .ThenInclude(c => c.Owner) |
| | 3 | 51 | | .Include(w => w.Members) |
| | 3 | 52 | | .ThenInclude(m => m.User) |
| | 3 | 53 | | .FirstOrDefaultAsync(w => w.Id == worldId); |
| | | 54 | | |
| | 3 | 55 | | if (world == null) |
| | 1 | 56 | | return null; |
| | | 57 | | |
| | | 58 | | // Check access via membership service |
| | 2 | 59 | | if (!await _membershipService.UserHasAccessAsync(worldId, userId)) |
| | 1 | 60 | | return null; |
| | | 61 | | |
| | 1 | 62 | | return MapToDetailDto(world); |
| | 3 | 63 | | } |
| | | 64 | | |
| | | 65 | | public async Task<WorldDto> CreateWorldAsync(WorldCreateDto dto, Guid userId) |
| | | 66 | | { |
| | 6 | 67 | | var user = await _context.Users.FindAsync(userId); |
| | 6 | 68 | | if (user == null) |
| | 1 | 69 | | throw new InvalidOperationException("User not found"); |
| | | 70 | | |
| | 5 | 71 | | _logger.LogDebugSanitized("Creating world '{Name}' for user {UserId}", dto.Name, userId); |
| | | 72 | | |
| | 5 | 73 | | var now = DateTime.UtcNow; |
| | | 74 | | |
| | | 75 | | // Generate unique slug for this owner |
| | 5 | 76 | | var slug = await GenerateUniqueWorldSlugAsync(dto.Name, userId); |
| | | 77 | | |
| | | 78 | | // Create the World entity |
| | 5 | 79 | | var world = new World |
| | 5 | 80 | | { |
| | 5 | 81 | | Id = Guid.NewGuid(), |
| | 5 | 82 | | Name = dto.Name, |
| | 5 | 83 | | Slug = slug, |
| | 5 | 84 | | Description = dto.Description, |
| | 5 | 85 | | OwnerId = userId, |
| | 5 | 86 | | CreatedAt = now, |
| | 5 | 87 | | IsPublic = false, |
| | 5 | 88 | | PublicSlug = null |
| | 5 | 89 | | }; |
| | 5 | 90 | | _context.Worlds.Add(world); |
| | | 91 | | |
| | | 92 | | // Create default Wiki articles |
| | 5 | 93 | | var wikiArticles = new[] |
| | 5 | 94 | | { |
| | 5 | 95 | | new Article |
| | 5 | 96 | | { |
| | 5 | 97 | | Id = Guid.NewGuid(), |
| | 5 | 98 | | Title = "Bestiary", |
| | 5 | 99 | | Slug = "bestiary", |
| | 5 | 100 | | Body = "# Bestiary\n\nA collection of creatures and monsters encountered in your adventures.", |
| | 5 | 101 | | Type = ArticleType.WikiArticle, |
| | 5 | 102 | | Visibility = ArticleVisibility.Public, |
| | 5 | 103 | | WorldId = world.Id, |
| | 5 | 104 | | CreatedBy = userId, |
| | 5 | 105 | | CreatedAt = now, |
| | 5 | 106 | | EffectiveDate = now, |
| | 5 | 107 | | IconEmoji = "🐉" |
| | 5 | 108 | | }, |
| | 5 | 109 | | new Article |
| | 5 | 110 | | { |
| | 5 | 111 | | Id = Guid.NewGuid(), |
| | 5 | 112 | | Title = "Characters", |
| | 5 | 113 | | Slug = "characters", |
| | 5 | 114 | | Body = "# Characters\n\nNPCs and notable figures in your world.", |
| | 5 | 115 | | Type = ArticleType.WikiArticle, |
| | 5 | 116 | | Visibility = ArticleVisibility.Public, |
| | 5 | 117 | | WorldId = world.Id, |
| | 5 | 118 | | CreatedBy = userId, |
| | 5 | 119 | | CreatedAt = now, |
| | 5 | 120 | | EffectiveDate = now, |
| | 5 | 121 | | IconEmoji = "👤" |
| | 5 | 122 | | }, |
| | 5 | 123 | | new Article |
| | 5 | 124 | | { |
| | 5 | 125 | | Id = Guid.NewGuid(), |
| | 5 | 126 | | Title = "Factions", |
| | 5 | 127 | | Slug = "factions", |
| | 5 | 128 | | Body = "# Factions\n\nOrganizations, guilds, and groups that shape your world.", |
| | 5 | 129 | | Type = ArticleType.WikiArticle, |
| | 5 | 130 | | Visibility = ArticleVisibility.Public, |
| | 5 | 131 | | WorldId = world.Id, |
| | 5 | 132 | | CreatedBy = userId, |
| | 5 | 133 | | CreatedAt = now, |
| | 5 | 134 | | EffectiveDate = now, |
| | 5 | 135 | | IconEmoji = "⚔️" |
| | 5 | 136 | | }, |
| | 5 | 137 | | new Article |
| | 5 | 138 | | { |
| | 5 | 139 | | Id = Guid.NewGuid(), |
| | 5 | 140 | | Title = "Locations", |
| | 5 | 141 | | Slug = "locations", |
| | 5 | 142 | | Body = "# Locations\n\nPlaces of interest, cities, dungeons, and landmarks.", |
| | 5 | 143 | | Type = ArticleType.WikiArticle, |
| | 5 | 144 | | Visibility = ArticleVisibility.Public, |
| | 5 | 145 | | WorldId = world.Id, |
| | 5 | 146 | | CreatedBy = userId, |
| | 5 | 147 | | CreatedAt = now, |
| | 5 | 148 | | EffectiveDate = now, |
| | 5 | 149 | | IconEmoji = "🗺️" |
| | 5 | 150 | | } |
| | 5 | 151 | | }; |
| | 5 | 152 | | _context.Articles.AddRange(wikiArticles); |
| | | 153 | | |
| | | 154 | | // Create default Player Character |
| | 5 | 155 | | var newCharacter = new Article |
| | 5 | 156 | | { |
| | 5 | 157 | | Id = Guid.NewGuid(), |
| | 5 | 158 | | Title = "New Character", |
| | 5 | 159 | | Slug = "new-character", |
| | 5 | 160 | | Body = "# New Character\n\nDescribe your character here. Add their backstory, personality, and goals.", |
| | 5 | 161 | | Type = ArticleType.Character, |
| | 5 | 162 | | Visibility = ArticleVisibility.Public, |
| | 5 | 163 | | WorldId = world.Id, |
| | 5 | 164 | | CreatedBy = userId, |
| | 5 | 165 | | PlayerId = userId, |
| | 5 | 166 | | CreatedAt = now, |
| | 5 | 167 | | EffectiveDate = now, |
| | 5 | 168 | | IconEmoji = "🧙" |
| | 5 | 169 | | }; |
| | 5 | 170 | | _context.Articles.Add(newCharacter); |
| | | 171 | | |
| | | 172 | | // Create default Campaign |
| | 5 | 173 | | var campaign = new Campaign |
| | 5 | 174 | | { |
| | 5 | 175 | | Id = Guid.NewGuid(), |
| | 5 | 176 | | Name = "Campaign 1", |
| | 5 | 177 | | Description = "Your first campaign adventure begins here.", |
| | 5 | 178 | | WorldId = world.Id, |
| | 5 | 179 | | OwnerId = userId, |
| | 5 | 180 | | CreatedAt = now |
| | 5 | 181 | | }; |
| | 5 | 182 | | _context.Campaigns.Add(campaign); |
| | | 183 | | |
| | | 184 | | // Create default Arc under the campaign |
| | 5 | 185 | | var arc = new Arc |
| | 5 | 186 | | { |
| | 5 | 187 | | Id = Guid.NewGuid(), |
| | 5 | 188 | | Name = "Arc 1", |
| | 5 | 189 | | Description = "The first chapter of your adventure.", |
| | 5 | 190 | | CampaignId = campaign.Id, |
| | 5 | 191 | | SortOrder = 1, |
| | 5 | 192 | | CreatedBy = userId, |
| | 5 | 193 | | CreatedAt = now |
| | 5 | 194 | | }; |
| | 5 | 195 | | _context.Arcs.Add(arc); |
| | | 196 | | |
| | 5 | 197 | | await _context.SaveChangesAsync(); |
| | | 198 | | |
| | 5 | 199 | | _logger.LogDebug("Created world {WorldId} with default content for user {UserId}", world.Id, userId); |
| | | 200 | | |
| | 5 | 201 | | world.Owner = user; |
| | 5 | 202 | | return MapToDto(world); |
| | 5 | 203 | | } |
| | | 204 | | |
| | | 205 | | public async Task<WorldDto?> UpdateWorldAsync(Guid worldId, WorldUpdateDto dto, Guid userId) |
| | | 206 | | { |
| | 3 | 207 | | var world = await _context.Worlds |
| | 3 | 208 | | .Include(w => w.Owner) |
| | 3 | 209 | | .Include(w => w.Campaigns) |
| | 3 | 210 | | .FirstOrDefaultAsync(w => w.Id == worldId); |
| | | 211 | | |
| | 3 | 212 | | if (world == null) |
| | 1 | 213 | | return null; |
| | | 214 | | |
| | | 215 | | // Only owner can update |
| | 2 | 216 | | if (world.OwnerId != userId) |
| | 1 | 217 | | return null; |
| | | 218 | | |
| | | 219 | | // If name changed, regenerate slug |
| | 1 | 220 | | if (world.Name != dto.Name) |
| | | 221 | | { |
| | 1 | 222 | | world.Slug = await GenerateUniqueWorldSlugAsync(dto.Name, userId, world.Id); |
| | | 223 | | } |
| | | 224 | | |
| | 1 | 225 | | world.Name = dto.Name; |
| | 1 | 226 | | world.Description = dto.Description; |
| | | 227 | | |
| | | 228 | | // Handle public visibility changes if specified |
| | 1 | 229 | | if (dto.IsPublic.HasValue) |
| | | 230 | | { |
| | 0 | 231 | | if (dto.IsPublic.Value) |
| | | 232 | | { |
| | | 233 | | // Making world public - require a valid public slug |
| | 0 | 234 | | if (string.IsNullOrWhiteSpace(dto.PublicSlug)) |
| | | 235 | | { |
| | 0 | 236 | | _logger.LogWarning("Attempted to make world {WorldId} public without a public slug", worldId); |
| | 0 | 237 | | return null; |
| | | 238 | | } |
| | | 239 | | |
| | 0 | 240 | | var normalizedSlug = dto.PublicSlug.Trim().ToLowerInvariant(); |
| | | 241 | | |
| | | 242 | | // Validate slug format via public sharing service |
| | 0 | 243 | | var validationError = _publicSharingService.ValidatePublicSlug(normalizedSlug); |
| | 0 | 244 | | if (validationError != null) |
| | | 245 | | { |
| | 0 | 246 | | _logger.LogWarningSanitized("Invalid public slug '{Slug}' for world {WorldId}: {Error}", |
| | 0 | 247 | | normalizedSlug, worldId, validationError); |
| | 0 | 248 | | return null; |
| | | 249 | | } |
| | | 250 | | |
| | | 251 | | // Check availability via public sharing service |
| | 0 | 252 | | if (!await _publicSharingService.IsPublicSlugAvailableAsync(normalizedSlug, worldId)) |
| | | 253 | | { |
| | 0 | 254 | | _logger.LogWarningSanitized("Public slug '{Slug}' is already taken", normalizedSlug); |
| | 0 | 255 | | return null; |
| | | 256 | | } |
| | | 257 | | |
| | 0 | 258 | | world.IsPublic = true; |
| | 0 | 259 | | world.PublicSlug = normalizedSlug; |
| | | 260 | | |
| | 0 | 261 | | _logger.LogDebugSanitized("World {WorldId} is now public with slug '{PublicSlug}'", worldId, normalizedS |
| | 0 | 262 | | } |
| | | 263 | | else |
| | | 264 | | { |
| | | 265 | | // Making world private - clear public slug |
| | 0 | 266 | | world.IsPublic = false; |
| | 0 | 267 | | world.PublicSlug = null; |
| | | 268 | | |
| | 0 | 269 | | _logger.LogDebug("World {WorldId} is now private", worldId); |
| | | 270 | | } |
| | | 271 | | } |
| | | 272 | | |
| | 1 | 273 | | await _context.SaveChangesAsync(); |
| | | 274 | | |
| | 1 | 275 | | _logger.LogDebug("Updated world {WorldId}", worldId); |
| | | 276 | | |
| | 1 | 277 | | return MapToDto(world); |
| | 3 | 278 | | } |
| | | 279 | | |
| | | 280 | | public async Task<WorldDto?> GetWorldBySlugAsync(string slug, Guid userId) |
| | | 281 | | { |
| | 3 | 282 | | var world = await _context.Worlds |
| | 3 | 283 | | .AsNoTracking() |
| | 3 | 284 | | .Include(w => w.Owner) |
| | 3 | 285 | | .Include(w => w.Campaigns) |
| | 3 | 286 | | .Include(w => w.Members) |
| | 3 | 287 | | .FirstOrDefaultAsync(w => w.Slug == slug && w.Members.Any(m => m.UserId == userId)); |
| | | 288 | | |
| | 3 | 289 | | if (world == null) |
| | 2 | 290 | | return null; |
| | | 291 | | |
| | 1 | 292 | | return MapToDto(world); |
| | 3 | 293 | | } |
| | | 294 | | |
| | | 295 | | /// <summary> |
| | | 296 | | /// Generate a unique slug for a world within an owner's worlds. |
| | | 297 | | /// </summary> |
| | | 298 | | private async Task<string> GenerateUniqueWorldSlugAsync(string name, Guid ownerId, Guid? excludeWorldId = null) |
| | | 299 | | { |
| | 6 | 300 | | var baseSlug = SlugGenerator.GenerateSlug(name); |
| | | 301 | | |
| | 6 | 302 | | var existingSlugsQuery = _context.Worlds |
| | 6 | 303 | | .AsNoTracking() |
| | 6 | 304 | | .Where(w => w.OwnerId == ownerId); |
| | | 305 | | |
| | 6 | 306 | | if (excludeWorldId.HasValue) |
| | | 307 | | { |
| | 1 | 308 | | existingSlugsQuery = existingSlugsQuery.Where(w => w.Id != excludeWorldId.Value); |
| | | 309 | | } |
| | | 310 | | |
| | 6 | 311 | | var existingSlugs = await existingSlugsQuery |
| | 6 | 312 | | .Select(w => w.Slug) |
| | 6 | 313 | | .ToHashSetAsync(); |
| | | 314 | | |
| | 6 | 315 | | return SlugGenerator.GenerateUniqueSlug(baseSlug, existingSlugs); |
| | 6 | 316 | | } |
| | | 317 | | |
| | | 318 | | private static WorldDto MapToDto(World world) |
| | | 319 | | { |
| | 10 | 320 | | return new WorldDto |
| | 10 | 321 | | { |
| | 10 | 322 | | Id = world.Id, |
| | 10 | 323 | | Name = world.Name, |
| | 10 | 324 | | Slug = world.Slug, |
| | 10 | 325 | | Description = world.Description, |
| | 10 | 326 | | OwnerId = world.OwnerId, |
| | 10 | 327 | | OwnerName = world.Owner?.DisplayName ?? "Unknown", |
| | 10 | 328 | | CreatedAt = world.CreatedAt, |
| | 10 | 329 | | CampaignCount = world.Campaigns?.Count ?? 0, |
| | 10 | 330 | | MemberCount = world.Members?.Count ?? 0, |
| | 10 | 331 | | IsPublic = world.IsPublic, |
| | 10 | 332 | | PublicSlug = world.PublicSlug |
| | 10 | 333 | | }; |
| | | 334 | | } |
| | | 335 | | |
| | | 336 | | private static WorldDetailDto MapToDetailDto(World world) |
| | | 337 | | { |
| | 1 | 338 | | return new WorldDetailDto |
| | 1 | 339 | | { |
| | 1 | 340 | | Id = world.Id, |
| | 1 | 341 | | Name = world.Name, |
| | 1 | 342 | | Slug = world.Slug, |
| | 1 | 343 | | Description = world.Description, |
| | 1 | 344 | | OwnerId = world.OwnerId, |
| | 1 | 345 | | OwnerName = world.Owner?.DisplayName ?? "Unknown", |
| | 1 | 346 | | CreatedAt = world.CreatedAt, |
| | 1 | 347 | | CampaignCount = world.Campaigns?.Count ?? 0, |
| | 1 | 348 | | MemberCount = world.Members?.Count ?? 0, |
| | 1 | 349 | | IsPublic = world.IsPublic, |
| | 1 | 350 | | PublicSlug = world.PublicSlug, |
| | 0 | 351 | | Campaigns = world.Campaigns?.Select(c => new CampaignDto |
| | 0 | 352 | | { |
| | 0 | 353 | | Id = c.Id, |
| | 0 | 354 | | WorldId = c.WorldId, |
| | 0 | 355 | | Name = c.Name, |
| | 0 | 356 | | Description = c.Description, |
| | 0 | 357 | | OwnerId = c.OwnerId, |
| | 0 | 358 | | OwnerName = c.Owner?.DisplayName ?? "Unknown", |
| | 0 | 359 | | CreatedAt = c.CreatedAt, |
| | 0 | 360 | | StartedAt = c.StartedAt, |
| | 0 | 361 | | EndedAt = c.EndedAt |
| | 0 | 362 | | }).ToList() ?? new List<CampaignDto>(), |
| | 2 | 363 | | Members = world.Members?.Select(m => new WorldMemberDto |
| | 2 | 364 | | { |
| | 2 | 365 | | Id = m.Id, |
| | 2 | 366 | | UserId = m.UserId, |
| | 2 | 367 | | DisplayName = m.User?.DisplayName ?? "Unknown", |
| | 2 | 368 | | Email = m.User?.Email ?? "", |
| | 2 | 369 | | AvatarUrl = m.User?.AvatarUrl, |
| | 2 | 370 | | Role = m.Role, |
| | 2 | 371 | | JoinedAt = m.JoinedAt, |
| | 2 | 372 | | InvitedBy = m.InvitedBy |
| | 2 | 373 | | }).ToList() ?? new List<WorldMemberDto>() |
| | 1 | 374 | | }; |
| | | 375 | | } |
| | | 376 | | } |