using LiteCharms.Extensions; using LiteCharms.Features.Shop.CartPackages.Models; using LiteCharms.Features.Shop.Postgres; namespace LiteCharms.Features.CartPackages.Queries.Handlers; public class GetPackageItemsQueryHandler(IDbContextFactory contextFactory) : IRequestHandler> { public async ValueTask> Handle(GetPackageItemsQuery request, CancellationToken cancellationToken) { try { using var context = await contextFactory.CreateDbContextAsync(cancellationToken); if (!await context.Packages.AnyAsync(p => p.Id == request.PackageId, cancellationToken)) return Result.Fail($"Package could not be found with ID {request.PackageId}"); var items = await context.PackageItems.AsNoTracking() .OrderByDescending(o => o.CreatedAt) .Where(p => p.PackageId == request.PackageId) .ToArrayAsync(cancellationToken); return items?.Length > 0 ? Result.Ok(items.Select(i => i.ToModel()).ToArray()) : Result.Fail($"Could not find package items by package ID {request.PackageId}"); } catch (Exception ex) { return Result.Fail(new Error(ex.Message).CausedBy(ex)); } } }