package com.lanyuanxiaoyao.digtal.market.runner

import com.lanyuanxiaoyao.digtal.market.ArticleRepository
import com.lanyuanxiaoyao.digtal.market.sender.DingtalkSender
import jakarta.annotation.Resource
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service

@Service
class PushRunner : Runner {
    private val logger = LoggerFactory.getLogger(javaClass)

    @Resource
    private lateinit var articleRepository: ArticleRepository

    @Scheduled(cron = "0 0 0,6,12,18 * * ?")
    override fun run() {
        val articles = articleRepository.findAll { root, _, builder ->
            builder.or(
                builder.equal(root.get<Boolean>("pushed"), false),
                builder.isNull(root.get<Boolean>("pushed")),
            )
        }
        try {
            DingtalkSender().send("近期要闻", mapOf("articles" to articles))
            articles.forEach { articleRepository.updatePushedById(it.id, true) }
        } catch (e: RuntimeException) {
            logger.error("发送失败", e)
        }
    }
}