package com.lanyuanxiaoyao.digtal.market

import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.Id
import java.util.Date
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional

@Entity
class Article(
    @Id var id: String,
    var code: String,
    var url: String,
    var title: String?,
    var author: String?,
    var category: String?,
    @Column(columnDefinition = "longtext") var text: String?,
    @Column(columnDefinition = "longtext") var html: String?,
    var subtitle: String?,
    @Column(columnDefinition = "longtext") var description: String?,
    var score: Int?,
    var createTime: Date?,
    var pushed: Boolean?,
)

@Repository
interface ArticleRepository : JpaRepository<Article, String>, JpaSpecificationExecutor<Article> {
    fun findAllByDescriptionIsNullAndTextIsNotNull(): List<Article>
    fun findAllByHtmlIsNotNull(): List<Article>

    @Modifying
    @Transactional
    @Query("update Article article set article.pushed = :pushed where article.id = :id")
    fun updatePushedById(@Param("id") id: String, @Param("pushed") pushed: Boolean)

    @Query("select article.id from Article article where article.description is not null and article.subtitle is not null and article.score is not null")
    fun findAllId(): List<String>

    @Query("select new com.lanyuanxiaoyao.digtal.market.CountGroupByString(article.code, count(article.code)) from Article article group by article.code")
    fun countGroupByCode(): List<CountGroupByString>
}

data class CountGroupByString(
    val key: String,
    val count: Long,
)
