using LiteCharms.Infrastructure.Database; namespace LiteCharms.Features.Customers.Commands.Handlers; public class RefundCustomerCommandHandler(IDbContextFactory contextFactory) : IRequestHandler> { public async ValueTask> Handle(RefundCustomerCommand request, CancellationToken cancellationToken) { try { using var context = await contextFactory.CreateDbContextAsync(cancellationToken); if(!await context.Orders.AnyAsync(o => o.Id == request.OrderId, cancellationToken)) return Result.Fail(new Error($"Order with Id: {request.OrderId} does not exist")); if (!await context.Customers.AnyAsync(c => c.Id == request.CustomerId, cancellationToken)) return Result.Fail(new Error($"Customer with Id: {request.CustomerId} does not exist")); if(!await context.Orders.AnyAsync(o => o.Id == request.OrderId && o.CustomerId == request.CustomerId, cancellationToken)) return Result.Fail(new Error($"Order with Id: {request.OrderId} does not belong to Customer with Id: {request.CustomerId}")); var refund = context.OrderRefunds.Add(new Entities.OrderRefund { OrderId = request.OrderId, Reason = request.Reason, Amount = request.Amount }); return await context.SaveChangesAsync(cancellationToken) > 0 ? Result.Ok(refund.Entity.Id) : Result.Fail(new Error($"Failed to create refund for OrderId: {request.OrderId}")); } catch (Exception ex) { return Result.Fail(new Error(ex.Message).CausedBy(ex)); } } }