package handlers

import (
	"strconv"

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

// AdminGetSearchLogs 获取搜索记录列表（后台）
func AdminGetSearchLogs(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))

	logs, total, err := repositories.GetSearchLogs(page, pageSize)
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	res := gin.H{
		"list":  logs,
		"total": total,
		"page":  page,
		"size":  pageSize,
	}

	utils.Success(c, res)
}

// AdminDeleteSearchLog 删除搜索记录
func AdminDeleteSearchLog(c *gin.Context) {
	idStr := c.Param("id")
	var id uint
	if _, err := strconv.ParseUint(idStr, 10, 32); err != nil {
		utils.Error(c, 400, "Invalid search log ID")
		return
	}

	if err := repositories.DeleteSearchLog(id); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.SuccessWithMsg(c, "Search log deleted successfully", nil)
}

// GetHotSearches 获取热门搜索关键词（公开）
func GetHotSearches(c *gin.Context) {
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
	days, _ := strconv.Atoi(c.DefaultQuery("days", "30"))

	keywords, err := repositories.GetHotKeywords(limit, days)
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	if keywords == nil {
		keywords = []repositories.HotKeyword{}
	}

	utils.Success(c, keywords)
}

// LogSearch 记录搜索（异步，不阻塞）
func LogSearch(keyword, searchType, userIP, userLocation string) {
	go func() {
		logEntry := &models.SearchLog{
			Keyword:      keyword,
			SearchType:   searchType,
			UserIP:       userIP,
			UserLocation: userLocation,
		}

		if err := repositories.CreateSearchLog(logEntry); err != nil {
			// Log error but don't fail
			// log.Printf("Failed to create search log: %v", err)
		}
	}()
}
