package repositories

import (
	"log"
	"time"

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

// GetSnippets 获取所有代码片段
func GetSnippets() ([]models.Snippet, error) {
	var snippets []models.Snippet
	err := config.DB.Model(&models.Snippet{}).
		Where("deleted_at = ?", 0).
		Order("created_at DESC").
		Find(&snippets).Error
	if err != nil {
		log.Printf("Error querying snippets: %v", err)
		return nil, err
	}
	return snippets, nil
}

// GetSnippetByID 根据ID获取代码片段
func GetSnippetByID(id string) (*models.Snippet, error) {
	var snippet models.Snippet
	err := config.DB.Model(&models.Snippet{}).
		Where("id = ? AND deleted_at = ?", id, 0).
		First(&snippet).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting snippet by ID: %v", err)
		return nil, err
	}

	// 更新查看次数
	config.DB.Model(&models.Snippet{}).
		Where("id = ?", id).
		UpdateColumn("view_count", gorm.Expr("view_count + ?", 1))

	return &snippet, nil
}

// BuildSnippetResponse 构建代码片段响应
func BuildSnippetResponse(snippet *models.Snippet) *models.SnippetResponse {
	return &models.SnippetResponse{
		ID:    snippet.ID,
		Title: snippet.Title,
		Code:  snippet.Code,
		Type:  snippet.Type,
	}
}

// BuildSnippetsResponse 构建代码片段列表响应
func BuildSnippetsResponse(snippets []models.Snippet) []models.SnippetResponse {
	var responses []models.SnippetResponse
	for _, snippet := range snippets {
		responses = append(responses, *BuildSnippetResponse(&snippet))
	}
	return responses
}

// CreateSnippet 创建代码片段
func CreateSnippet(snippet *models.Snippet) error {
	err := config.DB.Create(snippet).Error
	if err != nil {
		log.Printf("Error creating snippet: %v", err)
		return err
	}
	return nil
}

// UpdateSnippet 更新代码片段
func UpdateSnippet(snippet *models.Snippet) error {
	err := config.DB.Model(&models.Snippet{}).
		Where("id = ? AND deleted_at = ?", snippet.ID, 0).
		Updates(map[string]interface{}{
			"title":       snippet.Title,
			"code":        snippet.Code,
			"type":        snippet.Type,
			"description": snippet.Description,
			"updated_at":  time.Now().Unix(),
		}).Error
	if err != nil {
		log.Printf("Error updating snippet: %v", err)
		return err
	}
	return nil
}

// DeleteSnippet 删除代码片段 (Soft Delete)
func DeleteSnippet(id string) error {
	err := config.DB.Model(&models.Snippet{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting snippet: %v", err)
		return err
	}
	return nil
}

// GetAdminSnippets 获取后台代码片段列表 (分页)
func GetAdminSnippets(page, pageSize int) ([]models.Snippet, int, error) {
	offset := (page - 1) * pageSize

	var snippets []models.Snippet
	var total int64

	// 获取总数
	err := config.DB.Model(&models.Snippet{}).
		Where("deleted_at = ?", 0).
		Count(&total).Error
	if err != nil {
		log.Printf("Error getting snippet count: %v", err)
		return nil, 0, err
	}

	// 获取列表
	err = config.DB.Model(&models.Snippet{}).
		Where("deleted_at = ?", 0).
		Order("created_at DESC").
		Limit(pageSize).
		Offset(offset).
		Find(&snippets).Error
	if err != nil {
		log.Printf("Error querying admin snippets: %v", err)
		return nil, 0, err
	}

	return snippets, int(total), nil
}
