| | | 1 | | using Chronicis.Api.Data; |
| | | 2 | | using Chronicis.Api.Models; |
| | | 3 | | using Chronicis.Shared.DTOs.Quests; |
| | | 4 | | using Chronicis.Shared.Enums; |
| | | 5 | | using Chronicis.Shared.Extensions; |
| | | 6 | | using Chronicis.Shared.Models; |
| | | 7 | | using Microsoft.EntityFrameworkCore; |
| | | 8 | | |
| | | 9 | | namespace Chronicis.Api.Services; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Service for Quest operations with world membership authorization. |
| | | 13 | | /// </summary> |
| | | 14 | | public class QuestService : IQuestService |
| | | 15 | | { |
| | | 16 | | private readonly ChronicisDbContext _context; |
| | | 17 | | private readonly ILogger<QuestService> _logger; |
| | | 18 | | |
| | 18 | 19 | | public QuestService(ChronicisDbContext context, ILogger<QuestService> logger) |
| | | 20 | | { |
| | 18 | 21 | | _context = context; |
| | 18 | 22 | | _logger = logger; |
| | 18 | 23 | | } |
| | | 24 | | |
| | | 25 | | public async Task<ServiceResult<List<QuestDto>>> GetQuestsByArcAsync(Guid arcId, Guid userId) |
| | | 26 | | { |
| | | 27 | | // Check if user has access to this arc via world membership |
| | 4 | 28 | | var arc = await _context.Arcs |
| | 4 | 29 | | .AsNoTracking() |
| | 4 | 30 | | .Include(a => a.Campaign) |
| | 4 | 31 | | .FirstOrDefaultAsync(a => a.Id == arcId); |
| | | 32 | | |
| | 4 | 33 | | if (arc == null) |
| | | 34 | | { |
| | 1 | 35 | | return ServiceResult<List<QuestDto>>.NotFound("Arc not found"); |
| | | 36 | | } |
| | | 37 | | |
| | | 38 | | // Check world membership |
| | 3 | 39 | | var member = await _context.WorldMembers |
| | 3 | 40 | | .AsNoTracking() |
| | 3 | 41 | | .FirstOrDefaultAsync(m => m.WorldId == arc.Campaign.WorldId && m.UserId == userId); |
| | | 42 | | |
| | 3 | 43 | | if (member == null) |
| | | 44 | | { |
| | | 45 | | // Don't disclose arc existence to non-members |
| | 1 | 46 | | return ServiceResult<List<QuestDto>>.NotFound("Arc not found"); |
| | | 47 | | } |
| | | 48 | | |
| | 2 | 49 | | var isGM = member.Role == WorldRole.GM; |
| | | 50 | | |
| | | 51 | | // Build query - filter IsGmOnly for non-GM users |
| | 2 | 52 | | var query = _context.Quests |
| | 2 | 53 | | .AsNoTracking() |
| | 2 | 54 | | .Where(q => q.ArcId == arcId); |
| | | 55 | | |
| | 2 | 56 | | if (!isGM) |
| | | 57 | | { |
| | 1 | 58 | | query = query.Where(q => !q.IsGmOnly); |
| | | 59 | | } |
| | | 60 | | |
| | 2 | 61 | | var quests = await query |
| | 2 | 62 | | .OrderBy(q => q.SortOrder) |
| | 2 | 63 | | .ThenByDescending(q => q.UpdatedAt) |
| | 2 | 64 | | .Select(q => new QuestDto |
| | 2 | 65 | | { |
| | 2 | 66 | | Id = q.Id, |
| | 2 | 67 | | ArcId = q.ArcId, |
| | 2 | 68 | | Title = q.Title, |
| | 2 | 69 | | Description = q.Description, |
| | 2 | 70 | | Status = q.Status, |
| | 2 | 71 | | IsGmOnly = q.IsGmOnly, |
| | 2 | 72 | | SortOrder = q.SortOrder, |
| | 2 | 73 | | CreatedBy = q.CreatedBy, |
| | 2 | 74 | | CreatedByName = q.Creator.DisplayName, |
| | 2 | 75 | | CreatedAt = q.CreatedAt, |
| | 2 | 76 | | UpdatedAt = q.UpdatedAt, |
| | 2 | 77 | | RowVersion = Convert.ToBase64String(q.RowVersion), |
| | 2 | 78 | | UpdateCount = q.Updates.Count |
| | 2 | 79 | | }) |
| | 2 | 80 | | .ToListAsync(); |
| | | 81 | | |
| | 2 | 82 | | _logger.LogDebug("Retrieved {Count} quests for arc {ArcId} for user {UserId} (GM: {IsGM})", |
| | 2 | 83 | | quests.Count, arcId, userId, isGM); |
| | | 84 | | |
| | 2 | 85 | | return ServiceResult<List<QuestDto>>.Success(quests); |
| | 4 | 86 | | } |
| | | 87 | | |
| | | 88 | | public async Task<ServiceResult<QuestDto>> GetQuestAsync(Guid questId, Guid userId) |
| | | 89 | | { |
| | 4 | 90 | | var quest = await _context.Quests |
| | 4 | 91 | | .AsNoTracking() |
| | 4 | 92 | | .Include(q => q.Arc) |
| | 4 | 93 | | .ThenInclude(a => a.Campaign) |
| | 4 | 94 | | .Include(q => q.Creator) |
| | 4 | 95 | | .FirstOrDefaultAsync(q => q.Id == questId); |
| | | 96 | | |
| | 4 | 97 | | if (quest == null) |
| | | 98 | | { |
| | 0 | 99 | | return ServiceResult<QuestDto>.NotFound("Quest not found"); |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | // Check world membership |
| | 4 | 103 | | var member = await _context.WorldMembers |
| | 4 | 104 | | .AsNoTracking() |
| | 4 | 105 | | .FirstOrDefaultAsync(m => m.WorldId == quest.Arc.Campaign.WorldId && m.UserId == userId); |
| | | 106 | | |
| | 4 | 107 | | if (member == null) |
| | | 108 | | { |
| | | 109 | | // Don't disclose quest existence to non-members |
| | 1 | 110 | | return ServiceResult<QuestDto>.NotFound("Quest not found"); |
| | | 111 | | } |
| | | 112 | | |
| | 3 | 113 | | var isGM = member.Role == WorldRole.GM; |
| | | 114 | | |
| | | 115 | | // Non-GM users cannot see GM-only quests |
| | 3 | 116 | | if (quest.IsGmOnly && !isGM) |
| | | 117 | | { |
| | 1 | 118 | | return ServiceResult<QuestDto>.NotFound("Quest not found"); |
| | | 119 | | } |
| | | 120 | | |
| | 2 | 121 | | var updateCount = await _context.QuestUpdates |
| | 2 | 122 | | .CountAsync(qu => qu.QuestId == questId); |
| | | 123 | | |
| | 2 | 124 | | var dto = new QuestDto |
| | 2 | 125 | | { |
| | 2 | 126 | | Id = quest.Id, |
| | 2 | 127 | | ArcId = quest.ArcId, |
| | 2 | 128 | | Title = quest.Title, |
| | 2 | 129 | | Description = quest.Description, |
| | 2 | 130 | | Status = quest.Status, |
| | 2 | 131 | | IsGmOnly = quest.IsGmOnly, |
| | 2 | 132 | | SortOrder = quest.SortOrder, |
| | 2 | 133 | | CreatedBy = quest.CreatedBy, |
| | 2 | 134 | | CreatedByName = quest.Creator.DisplayName, |
| | 2 | 135 | | CreatedAt = quest.CreatedAt, |
| | 2 | 136 | | UpdatedAt = quest.UpdatedAt, |
| | 2 | 137 | | RowVersion = Convert.ToBase64String(quest.RowVersion), |
| | 2 | 138 | | UpdateCount = updateCount |
| | 2 | 139 | | }; |
| | | 140 | | |
| | 2 | 141 | | return ServiceResult<QuestDto>.Success(dto); |
| | 4 | 142 | | } |
| | | 143 | | |
| | | 144 | | public async Task<ServiceResult<QuestDto>> CreateQuestAsync(Guid arcId, QuestCreateDto dto, Guid userId) |
| | | 145 | | { |
| | | 146 | | // Validate input |
| | 3 | 147 | | if (string.IsNullOrWhiteSpace(dto.Title)) |
| | | 148 | | { |
| | 1 | 149 | | return ServiceResult<QuestDto>.ValidationError("Title is required"); |
| | | 150 | | } |
| | | 151 | | |
| | 2 | 152 | | if (dto.Title.Length > 300) |
| | | 153 | | { |
| | 1 | 154 | | return ServiceResult<QuestDto>.ValidationError("Title cannot exceed 300 characters"); |
| | | 155 | | } |
| | | 156 | | |
| | | 157 | | // Check if user has access to this arc and is GM |
| | 1 | 158 | | var arc = await _context.Arcs |
| | 1 | 159 | | .AsNoTracking() |
| | 1 | 160 | | .Include(a => a.Campaign) |
| | 1 | 161 | | .FirstOrDefaultAsync(a => a.Id == arcId); |
| | | 162 | | |
| | 1 | 163 | | if (arc == null) |
| | | 164 | | { |
| | 0 | 165 | | return ServiceResult<QuestDto>.NotFound("Arc not found"); |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | // Check world membership and GM role |
| | 1 | 169 | | var member = await _context.WorldMembers |
| | 1 | 170 | | .AsNoTracking() |
| | 1 | 171 | | .FirstOrDefaultAsync(m => m.WorldId == arc.Campaign.WorldId && m.UserId == userId); |
| | | 172 | | |
| | 1 | 173 | | if (member == null) |
| | | 174 | | { |
| | 0 | 175 | | return ServiceResult<QuestDto>.NotFound("Arc not found"); |
| | | 176 | | } |
| | | 177 | | |
| | 1 | 178 | | if (member.Role != WorldRole.GM) |
| | | 179 | | { |
| | 1 | 180 | | return ServiceResult<QuestDto>.Forbidden("Only GMs can create quests"); |
| | | 181 | | } |
| | | 182 | | |
| | 0 | 183 | | var now = DateTime.UtcNow; |
| | 0 | 184 | | var quest = new Quest |
| | 0 | 185 | | { |
| | 0 | 186 | | Id = Guid.NewGuid(), |
| | 0 | 187 | | ArcId = arcId, |
| | 0 | 188 | | Title = dto.Title.Trim(), |
| | 0 | 189 | | Description = dto.Description, |
| | 0 | 190 | | Status = dto.Status ?? QuestStatus.Active, |
| | 0 | 191 | | IsGmOnly = dto.IsGmOnly ?? false, |
| | 0 | 192 | | SortOrder = dto.SortOrder ?? 0, |
| | 0 | 193 | | CreatedBy = userId, |
| | 0 | 194 | | CreatedAt = now, |
| | 0 | 195 | | UpdatedAt = now |
| | 0 | 196 | | }; |
| | | 197 | | |
| | 0 | 198 | | _context.Quests.Add(quest); |
| | 0 | 199 | | await _context.SaveChangesAsync(); |
| | | 200 | | |
| | 0 | 201 | | _logger.LogDebugSanitized("Created quest '{Title}' in arc {ArcId} for user {UserId}", |
| | 0 | 202 | | dto.Title, arcId, userId); |
| | | 203 | | |
| | | 204 | | // Fetch creator name for DTO |
| | 0 | 205 | | var creator = await _context.Users.FindAsync(userId); |
| | | 206 | | |
| | 0 | 207 | | var resultDto = new QuestDto |
| | 0 | 208 | | { |
| | 0 | 209 | | Id = quest.Id, |
| | 0 | 210 | | ArcId = quest.ArcId, |
| | 0 | 211 | | Title = quest.Title, |
| | 0 | 212 | | Description = quest.Description, |
| | 0 | 213 | | Status = quest.Status, |
| | 0 | 214 | | IsGmOnly = quest.IsGmOnly, |
| | 0 | 215 | | SortOrder = quest.SortOrder, |
| | 0 | 216 | | CreatedBy = quest.CreatedBy, |
| | 0 | 217 | | CreatedByName = creator?.DisplayName ?? "Unknown", |
| | 0 | 218 | | CreatedAt = quest.CreatedAt, |
| | 0 | 219 | | UpdatedAt = quest.UpdatedAt, |
| | 0 | 220 | | RowVersion = Convert.ToBase64String(quest.RowVersion), |
| | 0 | 221 | | UpdateCount = 0 |
| | 0 | 222 | | }; |
| | | 223 | | |
| | 0 | 224 | | return ServiceResult<QuestDto>.Success(resultDto); |
| | 3 | 225 | | } |
| | | 226 | | |
| | | 227 | | public async Task<ServiceResult<QuestDto>> UpdateQuestAsync(Guid questId, QuestEditDto dto, Guid userId) |
| | | 228 | | { |
| | | 229 | | // Validate RowVersion is provided |
| | 3 | 230 | | if (string.IsNullOrWhiteSpace(dto.RowVersion)) |
| | | 231 | | { |
| | 1 | 232 | | return ServiceResult<QuestDto>.ValidationError("RowVersion is required for updates"); |
| | | 233 | | } |
| | | 234 | | |
| | | 235 | | byte[] rowVersion; |
| | | 236 | | try |
| | | 237 | | { |
| | 2 | 238 | | rowVersion = Convert.FromBase64String(dto.RowVersion); |
| | 2 | 239 | | } |
| | 0 | 240 | | catch (FormatException) |
| | | 241 | | { |
| | 0 | 242 | | return ServiceResult<QuestDto>.ValidationError("Invalid RowVersion format"); |
| | | 243 | | } |
| | | 244 | | |
| | | 245 | | // Validate title if provided |
| | 2 | 246 | | if (dto.Title != null && string.IsNullOrWhiteSpace(dto.Title)) |
| | | 247 | | { |
| | 0 | 248 | | return ServiceResult<QuestDto>.ValidationError("Title cannot be empty"); |
| | | 249 | | } |
| | | 250 | | |
| | 2 | 251 | | if (dto.Title != null && dto.Title.Length > 300) |
| | | 252 | | { |
| | 0 | 253 | | return ServiceResult<QuestDto>.ValidationError("Title cannot exceed 300 characters"); |
| | | 254 | | } |
| | | 255 | | |
| | | 256 | | // Find quest with tracking for update |
| | 2 | 257 | | var quest = await _context.Quests |
| | 2 | 258 | | .Include(q => q.Arc) |
| | 2 | 259 | | .ThenInclude(a => a.Campaign) |
| | 2 | 260 | | .Include(q => q.Creator) |
| | 2 | 261 | | .FirstOrDefaultAsync(q => q.Id == questId); |
| | | 262 | | |
| | 2 | 263 | | if (quest == null) |
| | | 264 | | { |
| | 0 | 265 | | return ServiceResult<QuestDto>.NotFound("Quest not found"); |
| | | 266 | | } |
| | | 267 | | |
| | | 268 | | // Check world membership and GM role |
| | 2 | 269 | | var member = await _context.WorldMembers |
| | 2 | 270 | | .AsNoTracking() |
| | 2 | 271 | | .FirstOrDefaultAsync(m => m.WorldId == quest.Arc.Campaign.WorldId && m.UserId == userId); |
| | | 272 | | |
| | 2 | 273 | | if (member == null) |
| | | 274 | | { |
| | 0 | 275 | | return ServiceResult<QuestDto>.NotFound("Quest not found"); |
| | | 276 | | } |
| | | 277 | | |
| | 2 | 278 | | if (member.Role != WorldRole.GM) |
| | | 279 | | { |
| | 1 | 280 | | return ServiceResult<QuestDto>.Forbidden("Only GMs can update quests"); |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | // Apply updates |
| | 1 | 284 | | if (dto.Title != null) |
| | | 285 | | { |
| | 1 | 286 | | quest.Title = dto.Title.Trim(); |
| | | 287 | | } |
| | | 288 | | |
| | 1 | 289 | | if (dto.Description != null) |
| | | 290 | | { |
| | 1 | 291 | | quest.Description = dto.Description; |
| | | 292 | | } |
| | | 293 | | |
| | 1 | 294 | | if (dto.Status.HasValue) |
| | | 295 | | { |
| | 1 | 296 | | quest.Status = dto.Status.Value; |
| | | 297 | | } |
| | | 298 | | |
| | 1 | 299 | | if (dto.IsGmOnly.HasValue) |
| | | 300 | | { |
| | 0 | 301 | | quest.IsGmOnly = dto.IsGmOnly.Value; |
| | | 302 | | } |
| | | 303 | | |
| | 1 | 304 | | if (dto.SortOrder.HasValue) |
| | | 305 | | { |
| | 0 | 306 | | quest.SortOrder = dto.SortOrder.Value; |
| | | 307 | | } |
| | | 308 | | |
| | 1 | 309 | | quest.UpdatedAt = DateTime.UtcNow; |
| | | 310 | | |
| | | 311 | | // Set original RowVersion for concurrency check |
| | 1 | 312 | | _context.Entry(quest).Property(q => q.RowVersion).OriginalValue = rowVersion; |
| | | 313 | | |
| | | 314 | | try |
| | | 315 | | { |
| | 1 | 316 | | await _context.SaveChangesAsync(); |
| | | 317 | | |
| | 1 | 318 | | _logger.LogDebug("Updated quest {QuestId} for user {UserId}", questId, userId); |
| | 1 | 319 | | } |
| | 0 | 320 | | catch (DbUpdateConcurrencyException) |
| | | 321 | | { |
| | | 322 | | // Reload current state from database |
| | 0 | 323 | | await _context.Entry(quest).ReloadAsync(); |
| | | 324 | | |
| | 0 | 325 | | var updateCount = await _context.QuestUpdates.CountAsync(qu => qu.QuestId == questId); |
| | | 326 | | |
| | 0 | 327 | | var currentDto = new QuestDto |
| | 0 | 328 | | { |
| | 0 | 329 | | Id = quest.Id, |
| | 0 | 330 | | ArcId = quest.ArcId, |
| | 0 | 331 | | Title = quest.Title, |
| | 0 | 332 | | Description = quest.Description, |
| | 0 | 333 | | Status = quest.Status, |
| | 0 | 334 | | IsGmOnly = quest.IsGmOnly, |
| | 0 | 335 | | SortOrder = quest.SortOrder, |
| | 0 | 336 | | CreatedBy = quest.CreatedBy, |
| | 0 | 337 | | CreatedByName = quest.Creator.DisplayName, |
| | 0 | 338 | | CreatedAt = quest.CreatedAt, |
| | 0 | 339 | | UpdatedAt = quest.UpdatedAt, |
| | 0 | 340 | | RowVersion = Convert.ToBase64String(quest.RowVersion), |
| | 0 | 341 | | UpdateCount = updateCount |
| | 0 | 342 | | }; |
| | | 343 | | |
| | 0 | 344 | | _logger.LogWarning("Concurrency conflict updating quest {QuestId}", questId); |
| | | 345 | | |
| | 0 | 346 | | return ServiceResult<QuestDto>.Conflict( |
| | 0 | 347 | | "Quest was modified by another user. Please reload and try again.", |
| | 0 | 348 | | currentDto); |
| | | 349 | | } |
| | | 350 | | |
| | | 351 | | // Fetch update count for result |
| | 1 | 352 | | var resultUpdateCount = await _context.QuestUpdates.CountAsync(qu => qu.QuestId == questId); |
| | | 353 | | |
| | 1 | 354 | | var resultDto = new QuestDto |
| | 1 | 355 | | { |
| | 1 | 356 | | Id = quest.Id, |
| | 1 | 357 | | ArcId = quest.ArcId, |
| | 1 | 358 | | Title = quest.Title, |
| | 1 | 359 | | Description = quest.Description, |
| | 1 | 360 | | Status = quest.Status, |
| | 1 | 361 | | IsGmOnly = quest.IsGmOnly, |
| | 1 | 362 | | SortOrder = quest.SortOrder, |
| | 1 | 363 | | CreatedBy = quest.CreatedBy, |
| | 1 | 364 | | CreatedByName = quest.Creator.DisplayName, |
| | 1 | 365 | | CreatedAt = quest.CreatedAt, |
| | 1 | 366 | | UpdatedAt = quest.UpdatedAt, |
| | 1 | 367 | | RowVersion = Convert.ToBase64String(quest.RowVersion), |
| | 1 | 368 | | UpdateCount = resultUpdateCount |
| | 1 | 369 | | }; |
| | | 370 | | |
| | 1 | 371 | | return ServiceResult<QuestDto>.Success(resultDto); |
| | 3 | 372 | | } |
| | | 373 | | |
| | | 374 | | public async Task<ServiceResult<bool>> DeleteQuestAsync(Guid questId, Guid userId) |
| | | 375 | | { |
| | 4 | 376 | | var quest = await _context.Quests |
| | 4 | 377 | | .Include(q => q.Arc) |
| | 4 | 378 | | .ThenInclude(a => a.Campaign) |
| | 4 | 379 | | .FirstOrDefaultAsync(q => q.Id == questId); |
| | | 380 | | |
| | 4 | 381 | | if (quest == null) |
| | | 382 | | { |
| | 1 | 383 | | return ServiceResult<bool>.NotFound("Quest not found"); |
| | | 384 | | } |
| | | 385 | | |
| | | 386 | | // Check world membership and GM role |
| | 3 | 387 | | var member = await _context.WorldMembers |
| | 3 | 388 | | .AsNoTracking() |
| | 3 | 389 | | .FirstOrDefaultAsync(m => m.WorldId == quest.Arc.Campaign.WorldId && m.UserId == userId); |
| | | 390 | | |
| | 3 | 391 | | if (member == null) |
| | | 392 | | { |
| | 0 | 393 | | return ServiceResult<bool>.NotFound("Quest not found"); |
| | | 394 | | } |
| | | 395 | | |
| | 3 | 396 | | if (member.Role != WorldRole.GM) |
| | | 397 | | { |
| | 1 | 398 | | return ServiceResult<bool>.Forbidden("Only GMs can delete quests"); |
| | | 399 | | } |
| | | 400 | | |
| | 2 | 401 | | _context.Quests.Remove(quest); |
| | 2 | 402 | | await _context.SaveChangesAsync(); |
| | | 403 | | |
| | 2 | 404 | | _logger.LogDebug("Deleted quest {QuestId} and its updates for user {UserId}", questId, userId); |
| | | 405 | | |
| | 2 | 406 | | return ServiceResult<bool>.Success(true); |
| | 4 | 407 | | } |
| | | 408 | | } |