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