using LiteCharms.Extensions; using LiteCharms.Infrastructure.Database; using LiteCharms.Models; namespace LiteCharms.Features.Products.Queries.Handlers; public class GetProductPriceQueryHandler(IDbContextFactory contextFactory) : IRequestHandler> { public async ValueTask> Handle(GetProductPriceQuery request, CancellationToken cancellationToken) { try { using var context = await contextFactory.CreateDbContextAsync(cancellationToken); var productPrice = await context.ProductPrices.AsNoTracking() .Where(pp => pp.ProductId == request.ProductId && pp.Active) .OrderByDescending(pp => pp.CreatedAt) .FirstOrDefaultAsync(cancellationToken); return productPrice is not null ? Result.Ok(productPrice.ToModel()) : Result.Fail(new Error($"Product price {request.ProductId} not found.")); } catch (Exception ex) { return Result.Fail(new Error(ex.Message).CausedBy(ex)); } } }