package com.lanyuanxiaoyao.digtal.market.controller

import com.lanyuanxiaoyao.digtal.market.ArticleRepository
import com.lanyuanxiaoyao.digtal.market.sites
import jakarta.annotation.Resource
import org.slf4j.LoggerFactory
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("overview")
class OverviewController {
    private val logger = LoggerFactory.getLogger(javaClass)

    @Resource
    private lateinit var articleRepository: ArticleRepository

    @GetMapping("news")
    fun news(
        @RequestParam("code", required = false) code: String?,
        @RequestParam("page", defaultValue = "1") page: Int,
        @RequestParam("count", defaultValue = "10") count: Int,
    ): Map<String, Any> {
        val request = PageRequest.of(page - 1, count, Sort.by(Sort.Direction.DESC, "createTime"))
        val result = articleRepository.findAll(request)
        return mapOf(
            "items" to result.content.map {
                val iframe = (sites.firstOrNull { site -> site.code == it.code }?.properties?.get("iframe")?: "false").toBoolean()
                mapOf(
                    "code" to it.code,
                    "title" to it.title,
                    "subtitle" to it.subtitle,
                    "author" to it.author,
                    "description" to it.description,
                    "url" to it.url,
                    "createTime" to it.createTime,
                    "iframe" to iframe,
                    "category" to it.category,
                )
            },
            "total" to result.totalElements,
        )
    }
}