package repositories

import (
	"log"
	"time"

	"github.com/niangaodev/art-code/config"
	"github.com/niangaodev/art-code/models"
)

// CreateUserAccessLog 创建用户访问日志
func CreateUserAccessLog(logEntry *models.UserAccessLog) error {
	if logEntry.AccessTime == 0 {
		logEntry.AccessTime = time.Now().Unix()
	}
	err := config.DB.Create(logEntry).Error
	if err != nil {
		log.Printf("Error creating user access log: %v", err)
		return err
	}
	return nil
}

// AccessStats 访问统计数据结构
type AccessStats struct {
	Date  string `json:"date"`
	Count int    `json:"count"`
}

// GetArticleAccessTrend 获取文章访问趋势
func GetArticleAccessTrend(startDate, endDate string) ([]AccessStats, error) {
	query := config.DB.Model(&models.UserAccessLog{}).
		Select("FROM_UNIXTIME(access_time, '%Y-%m-%d') as date, COUNT(*) as count")

	if startDate != "" {
		startUnix := parseDateToUnix(startDate, false)
		query = query.Where("access_time >= ?", startUnix)
	}
	if endDate != "" {
		endUnix := parseDateToUnix(endDate, true)
		query = query.Where("access_time <= ?", endUnix)
	}

	var results []AccessStats
	err := query.Group("date").
		Order("date ASC").
		Scan(&results).Error

	return results, err
}

// GetTopArticlesByAccess 获取访问量最高的文章
func GetTopArticlesByAccess(limit int) ([]struct {
	ArticleID int    `json:"article_id"`
	Title     string `json:"title"`
	Count     int    `json:"count"`
}, error) {
	var results []struct {
		ArticleID int    `json:"article_id"`
		Title     string `json:"title"`
		Count     int    `json:"count"`
	}
	err := config.DB.Model(&models.UserAccessLog{}).
		Select("user_access_logs.article_id, posts.title, COUNT(*) as count").
		Joins("JOIN posts ON user_access_logs.article_id = posts.id").
		Group("user_access_logs.article_id, posts.title").
		Order("count DESC").
		Limit(limit).
		Scan(&results).Error

	return results, err
}
