package repositories

import (
	"log"
	"time"

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

// CreateSearchLog 创建搜索记录
func CreateSearchLog(logEntry *models.SearchLog) error {
	err := config.DB.Create(logEntry).Error
	if err != nil {
		log.Printf("Error creating search log: %v", err)
		return err
	}
	return nil
}

// GetSearchLogs 获取搜索记录列表（分页）
func GetSearchLogs(page, pageSize int) ([]models.SearchLog, int64, error) {
	offset := (page - 1) * pageSize

	var logs []models.SearchLog
	var total int64

	// Count total
	err := config.DB.Model(&models.SearchLog{}).
		Where("deleted_at = ?", 0).
		Count(&total).Error
	if err != nil {
		log.Printf("Error counting search logs: %v", err)
		return nil, 0, err
	}

	// Get logs
	err = config.DB.Model(&models.SearchLog{}).
		Where("deleted_at = ?", 0).
		Order("created_at DESC").
		Limit(pageSize).
		Offset(offset).
		Find(&logs).Error

	if err != nil {
		log.Printf("Error querying search logs: %v", err)
		return nil, 0, err
	}

	return logs, total, nil
}

// DeleteSearchLog 删除搜索记录（软删除）
func DeleteSearchLog(id uint) error {
	err := config.DB.Model(&models.SearchLog{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting search log: %v", err)
		return err
	}
	return nil
}

// HotKeyword 热门搜索关键词
type HotKeyword struct {
	Keyword string `json:"keyword"`
	Count   int    `json:"count"`
}

// GetHotKeywords 获取热门搜索关键词
func GetHotKeywords(limit, days int) ([]HotKeyword, error) {
	if limit <= 0 {
		limit = 10
	}
	if days <= 0 {
		days = 30
	}

	since := time.Now().AddDate(0, 0, -days).Unix()

	var results []HotKeyword
	err := config.DB.Model(&models.SearchLog{}).
		Select("keyword, COUNT(*) as count").
		Where("deleted_at = ?", 0).
		Where("search_type = ?", "keyword").
		Where("created_at >= ?", since).
		Where("CHAR_LENGTH(keyword) >= ?", 2).
		Group("keyword").
		Order("count DESC").
		Limit(limit).
		Scan(&results).Error
	if err != nil {
		log.Printf("Error querying hot keywords: %v", err)
		return nil, err
	}

	return results, nil
}
