package handlers

import (
	"github.com/gin-gonic/gin"
	"github.com/niangaodev/art-code/repositories"
	"github.com/niangaodev/art-code/utils"
)

// GetDashboardStats 获取仪表盘统计数据
func GetDashboardStats(c *gin.Context) {
	startDate := c.Query("startDate")
	endDate := c.Query("endDate")

	// 1. 获取博文增长趋势
	postsTrend, err := repositories.GetNewPostsTrend(startDate, endDate)
	if err != nil {
		postsTrend = []repositories.TrendData{} // Fallback empty
	}

	// 2. 获取访客UV (根据IP)
	uvTrend, err := repositories.GetDailyUV(startDate, endDate)
	if err != nil {
		uvTrend = []repositories.UVTrendData{}
	}

	// 3. 用户画像-地域分布
	userRegions, err := repositories.GetUserRegions(startDate, endDate)
	if err != nil {
		userRegions = []struct {
			Region string
			Count  int
		}{}
	}

	// 4. 热门文章 Top 5
	// 优先使用访问日志统计，不足5条则用posts表的read_count补齐
	topPosts, err := repositories.GetTopArticlesByAccess(5)
	if err != nil {
		topPosts = []struct {
			ArticleID int    `json:"article_id"`
			Title     string `json:"title"`
			Count     int    `json:"count"`
		}{}
	}

	if len(topPosts) < 5 {
		// Fetch more than needed to ensure we find unique ones, or just fetch top 5
		dbPosts, err := repositories.GetTopPosts(10)
		if err == nil {
			// Create a map of existing IDs to avoid duplicates
			existingIDs := make(map[int]bool)
			for _, p := range topPosts {
				existingIDs[p.ArticleID] = true
			}

			for _, p := range dbPosts {
				if len(topPosts) >= 5 {
					break
				}
				if !existingIDs[int(p.ID)] {
					topPosts = append(topPosts, struct {
						ArticleID int    `json:"article_id"`
						Title     string `json:"title"`
						Count     int    `json:"count"`
					}{
						ArticleID: int(p.ID),
						Title:     p.Title,
						Count:     int(p.ReadCount),
					})
					existingIDs[int(p.ID)] = true
				}
			}
		}
	}

	// 5. 合作咨询总数
	inquiryCount, _ := repositories.GetInquiryCount()

	// 6. 作品总数
	workCount, _ := repositories.GetWorkCount()

	// 7. 文章总数
	postCount, _ := repositories.GetPostCount()

	utils.Success(c, gin.H{
		"postsTrend":   postsTrend,
		"uvTrend":      uvTrend,
		"userRegions":  userRegions,
		"topPosts":     topPosts,
		"inquiryCount": inquiryCount,
		"posts":        postCount,
		"works":        workCount,
	})
}
