using NetinaCMS.Repository.Repositories.Base.Contracts;

namespace NetinaCMS.Repository.Handlers.Blogs;

public class GetBlogQueryHandler : IRequestHandler<GetBlogQuery, BlogLDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public GetBlogQueryHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<BlogLDto> Handle(GetBlogQuery request, CancellationToken cancellationToken)
    {
        var blog = await _repositoryWrapper.SetRepository<Blog>()
            .TableNoTracking
            .Where(b => b.Id == request.Id)
            .Select(BlogMapper.ProjectToLDto)
            .FirstOrDefaultAsync(cancellationToken);

        if (blog == null)
            throw new AppException("Blog not found", ApiResultStatusCode.NotFound);

        return blog;
    }
}