using LiteCharms.Features.Shop.Postgres; namespace LiteCharms.Features.ShoppingCarts.Commands.Handlers; public class EmptyShoppingCartCommandHandler(IDbContextFactory contextFactory) : IRequestHandler { public async ValueTask Handle(EmptyShoppingCartCommand 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 could not be found with id {request.ShoppingCartId}"); if (await context.ShoppingCartItems.CountAsync(i => i.ShoppingCartId == request.ShoppingCartId, cancellationToken) == 0) return Result.Ok(); var cartItems = await context.ShoppingCartItems.Where(i => i.ShoppingCartId == request.ShoppingCartId).ToListAsync(cancellationToken); context.RemoveRange(cartItems); return await context.SaveChangesAsync(cancellationToken) > 0 ? Result.Ok() : Result.Fail($"Could not empty cart with id {request.ShoppingCartId}"); } catch (Exception ex) { return Result.Fail(new Error(ex.Message).CausedBy(ex)); } } }