using LiteCharms.Extensions; using LiteCharms.Features.ShoppingCarts.Queries; using LiteCharms.Infrastructure.Database; using LiteCharms.Models; namespace LiteCharms.Features.ShoppingCarts.Queries.Handlers; public class GetCustomerShoppingCartsQueryHandler(IDbContextFactory contextFactory) : IRequestHandler> { public async ValueTask> Handle(GetCustomerShoppingCartsQuery request, CancellationToken cancellationToken) { try { using var context = await contextFactory.CreateDbContextAsync(cancellationToken); if (!await context.Customers.AnyAsync(c => c.Id == request.CustomerId, cancellationToken)) return Result.Fail(new Error($"Customer with Id {request.CustomerId} does not exist.")); var shoppingCarts = await context.ShoppingCarts.Where(sc => sc.CustomerId == request.CustomerId).ToArrayAsync(cancellationToken); return shoppingCarts?.Length > 0 ? Result.Ok(shoppingCarts.Select(c => c.ToModel()).ToArray()) : Result.Fail(new Error($"No shopping carts found for customer with Id {request.CustomerId}.")); } catch (Exception ex) { return Result.Fail(new Error(ex.Message).CausedBy(ex)); } } }