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
}
