package cn.reghao.tnb.search.app.blog.db.repository;

import cn.reghao.tnb.search.app.blog.model.po.Category;
import cn.reghao.tnb.search.app.blog.model.vo.GroupCount;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @author reghao
 * @date 2024-01-29 09:24:29
 */
public interface CategoryRepository extends JpaRepository<Category, Integer> {
    List<Category> findAllByType(int type);
    Category findByName(String name);
    Category findByTypeAndName(int type, String name);

    @Query(value =
            "SELECT article.category_id as id, category.name, count(article.category_id) as total\n" +
                    "FROM blog_article as article\n" +
                    "INNER JOIN blog_category as category\n" +
                    "ON article.published is true and article.category_id=category.id\n" +
                    "GROUP BY id\n" +
                    "ORDER BY total DESC",
            nativeQuery = true)
    List<GroupCount> findCategoryGroup();

    @Query(value =
            "SELECT tag_id as id, category.name, count(articleTag.tag_id) as total\n" +
                    "FROM blog_article_tag as articleTag\n" +
                    "INNER JOIN blog_category as category\n" +
                    "INNER JOIN blog_article as article\n" +
                    "ON article.article_id=articleTag.article_id and article.published is true and articleTag.tag_id=category.id\n" +
                    "GROUP BY id\n" +
                    "ORDER BY total DESC",
            nativeQuery = true)
    List<GroupCount> findTagGroup();
}
