namespace Brizco.Repository.MartenHandlers.NewsFeeds;

public class GetNewsFeedsQueryHandler (IMartenRepositoryWrapper martenRepositoryWrapper,ICurrentUserService currentUserService) : IRequestHandler<GetNewsFeedsQuery,List<NewsFeed>>
{
    public async Task<List<NewsFeed>> Handle(GetNewsFeedsQuery request, CancellationToken cancellationToken)
    {
        if (currentUserService.ComplexId == null)
            throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is null");
        if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
            throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong");

        var count = request.Count ?? 5;
        var query = await martenRepositoryWrapper.SetRepository<NewsFeed>()
            .GetQueryAsync(q=>q.ComplexId == complexId);

        query = query.Skip(request.Page * count)
            .Take(count)
            .OrderByDescending(c=>c.CreatedAt);

        return await query.ToListAsync(cancellationToken);
    }
}