using LiteCharms.Extensions; using LiteCharms.Infrastructure.Database; using LiteCharms.Models; namespace LiteCharms.Features.ShoppingCarts.Queries.Handlers; public class GetShoppingCartItemsQueryHandler(IDbContextFactory contextFactory) : IRequestHandler> { public async ValueTask> Handle(GetShoppingCartItemsQuery request, CancellationToken cancellationToken) { try { using var context = await contextFactory.CreateDbContextAsync(cancellationToken); if (!await context.ShoppingCarts.AnyAsync(i => i.Id == request.ShoppingCartId, cancellationToken)) return Result.Fail($"Shopping cart could not be found with id {request.ShoppingCartId}"); var items = await context.ShoppingCartItems.AsNoTracking() .Where(i => i.ShoppingCartId == request.ShoppingCartId).ToArrayAsync(cancellationToken); return items?.Length > 0 ? Result.Ok(items.Select(i => i.ToModel()).ToArray()) : Result.Fail($"Failed to retrieve shopping cart items with id {request.ShoppingCartId}"); } catch (Exception ex) { return Result.Fail(new Error(ex.Message).CausedBy(ex)); } } }