using API.Data; using API.Models; using API.Services; using Microsoft.EntityFrameworkCore; using Model; namespace API.GraphQL; public class Query { private static string EnsureAuthenticated(IHttpContextAccessor? httpContextAccessor, ITokenService tokenService) { var httpContext = httpContextAccessor?.HttpContext; if (httpContext == null) throw new Exception("Authentication required. Please provide a valid authorization token."); var authHeader = httpContext.Request.Headers["Authorization"].FirstOrDefault(); if (string.IsNullOrWhiteSpace(authHeader)) throw new Exception("Authentication required. Please login to access this resource."); var token = authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) ? authHeader["Bearer ".Length..].Trim() : authHeader.Trim(); var username = tokenService.ValidateToken(token); if (string.IsNullOrEmpty(username)) throw new Exception("Invalid or expired authentication token. Please login again."); return username; } public async Task GetNote( [Service] AppDbContext db, [Service] IHttpContextAccessor httpContextAccessor, [Service] ITokenService tokenService, string cardName) { var username = EnsureAuthenticated(httpContextAccessor, tokenService); try { var note = await db.CardNotes.FirstOrDefaultAsync(n => n.CardName == cardName && n.Username == username); return note ?? new CardNote { Username = username, CardName = cardName, Note = "" }; } catch (Exception ex) { Console.WriteLine($"[WARNING] Could not retrieve note: {ex.Message}"); return new CardNote { Username = username, CardName = cardName, Note = "" }; } } public async Task> GetNotes( [Service] AppDbContext db, [Service] IHttpContextAccessor httpContextAccessor, [Service] ITokenService tokenService) { var username = EnsureAuthenticated(httpContextAccessor, tokenService); try { return await db.CardNotes.Where(n => n.Username == username).ToListAsync(); } catch (Exception ex) { Console.WriteLine($"[WARNING] Could not retrieve notes: {ex.Message}"); return new List(); } } public async Task> GetDecks( [Service] AppDbContext db, [Service] IHttpContextAccessor httpContextAccessor, [Service] ITokenService tokenService) { EnsureAuthenticated(httpContextAccessor, tokenService); try { return await db.UserDecks.OrderByDescending(d => d.UpdatedAt).ToListAsync(); } catch (Exception ex) { Console.WriteLine($"[WARNING] Could not retrieve decks: {ex.Message}"); return new List(); } } public async Task GetDeck( [Service] AppDbContext db, [Service] IHttpContextAccessor httpContextAccessor, [Service] ITokenService tokenService, Guid id) { EnsureAuthenticated(httpContextAccessor, tokenService); try { return await db.UserDecks.FindAsync(id); } catch (Exception ex) { Console.WriteLine($"[WARNING] Could not retrieve deck: {ex.Message}"); return null; } } }