package cn.reghao.tnb.search.app.blog.service;

import cn.reghao.tnb.common.web.ServletUtil;
import cn.reghao.tnb.search.app.blog.db.repository.ArticleViewRepository;
import cn.reghao.tnb.search.app.blog.model.po.ArticleView;
import cn.reghao.tnb.search.app.blog.model.vo.ArticleCount;
import cn.reghao.jutil.jdk.http.HeaderNames;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author reghao
 * @date 2024-02-05 14:29:51
 */
@Service
public class ArticleViewService {
    private final ArticleViewRepository articleViewRepository;

    public ArticleViewService(ArticleViewRepository articleViewRepository) {
        this.articleViewRepository = articleViewRepository;
    }

    public void incr(String articleId) {
        String sessionId = ServletUtil.getSessionId();
        ArticleView articleVisitor = articleViewRepository.findArticleViewByArticleIdAndSessionId(articleId, sessionId);
        if (articleVisitor == null) {
            String requestId = (String) ServletUtil.getRequest().getAttribute(HeaderNames.XRequestId);
            articleVisitor = new ArticleView(articleId, sessionId, requestId);
            articleViewRepository.save(articleVisitor);
        }
    }

    public int getViewCount(String articleId) {
        return articleViewRepository.countByArticleId(articleId);
    }

    public List<ArticleCount> getArticleCount(int size) {
        PageRequest pageRequest = PageRequest.of(0, size);
        return articleViewRepository.findViewCountByGroup(pageRequest);
    }
}
