using LiteCharms.Extensions; using LiteCharms.Infrastructure.Database; using LiteCharms.Models; namespace LiteCharms.Features.Quotes.Queries.Handlers; public class GetQuotesHandler(IDbContextFactory contextFactory) : IRequestHandler> { public async ValueTask> Handle(GetQuotesQuery request, CancellationToken cancellationToken) { try { var fromDate = request.From.ToDateTime(TimeOnly.MinValue); var toDate = request.To.ToDateTime(TimeOnly.MaxValue); using var context = await contextFactory.CreateDbContextAsync(cancellationToken); var quotes = await context.Quotes.AsNoTracking() .OrderByDescending(o => o.CreatedAt) .Where(o => o.CreatedAt >= fromDate && o.CreatedAt <= toDate) .Take(request.MaxRecords) .ToArrayAsync(cancellationToken); return quotes?.Length > 0 ? Result.Ok(quotes.Select(o => o.ToModel()).ToArray()) : Result.Fail(new Error($"No quotes found for the specified date range {request.From} - {request.To}.")); } catch (Exception ex) { return Result.Fail(new Error(ex.Message).CausedBy(ex)); } } }