using LiteCharms.Extensions; using LiteCharms.Infrastructure.Database; using LiteCharms.Models; namespace LiteCharms.Features.ShoppingCarts.Queries.Handlers; public class GetShoppingCartPackagesQueryHandler(IDbContextFactory contextFactory) : IRequestHandler> { public async ValueTask> Handle(GetShoppingCartPackagesQuery request, CancellationToken cancellationToken) { try { using var context = await contextFactory.CreateDbContextAsync(cancellationToken); if (!await context.ShoppingCarts.AnyAsync(c => c.Id == request.ShoppingCartId, cancellationToken)) return Result.Fail($"Shopping cart could not be found by ID {request.ShoppingCartId}"); var packages = await context.ShoppingCartPackages.AsNoTracking() .OrderByDescending(o => o.CreatedAt) .Where(cp => cp.ShoppingCartId == request.ShoppingCartId) .ToArrayAsync(cancellationToken); return packages?.Length > 0 ? Result.Ok(packages.Select(p => p.ToModel()).ToArray()) : Result.Fail($"Could not find packaged in shopping cart by ID {request.ShoppingCartId}"); } catch (Exception ex) { return Result.Fail(new Error(ex.Message).CausedBy(ex)); } } }