using LiteCharms.Infrastructure.Database; namespace LiteCharms.Features.ShoppingCarts.Commands.Handlers; public class RemovePackageFromShoppingCartCommandHandler(IDbContextFactory contextFactory) : IRequestHandler { public async ValueTask Handle(RemovePackageFromShoppingCartCommand 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}"); if (!await context.ShoppingCartPackages.AnyAsync(p => p.Id == request.ShoppingCartPackageId, cancellationToken)) return Result.Fail($"Shopping cart package {request.ShoppingCartPackageId} is not in the shopping cart {request.ShoppingCartId}"); var shoppingCartPackage = await context.ShoppingCartPackages.FirstOrDefaultAsync(cp => cp.Id == request.ShoppingCartPackageId, cancellationToken); if (shoppingCartPackage is null) return Result.Ok(); context.ShoppingCartPackages.Remove(shoppingCartPackage!); return await context.SaveChangesAsync(cancellationToken) > 0 ? Result.Ok() : Result.Fail($"Could remove package of id {request.ShoppingCartPackageId} from shopping cart {request.ShoppingCartId}"); } catch (Exception ex) { return Result.Fail(new Error(ex.Message).CausedBy(ex)); } } }