namespace Brizco.Repository.MartenHandlers.NewsFeeds;

public class ChangeNewsFeedPinCommandHandler(IMartenRepositoryWrapper martenRepositoryWrapper, ICurrentUserService currentUserService)
    : IRequestHandler<ChangeNewsFeedPinCommand, bool>
{
    public async Task<bool> Handle(ChangeNewsFeedPinCommand 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 ent = await martenRepositoryWrapper.SetRepository<NewsFeed>().GetEntityAsync(request.Id, cancellationToken);
        if (ent.ComplexId != complexId)
            throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong");
        ent.IsPin = request.IsPin;
        await martenRepositoryWrapper.SetRepository<NewsFeed>().AddOrUpdateEntityAsync(ent, cancellationToken);
        return true;
    }
}