package repositories

import (
	"log"
	"time"

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

// GetCategories 获取所有分类
func GetCategories() ([]models.Category, error) {
	var categories []models.Category
	err := config.DB.Model(&models.Category{}).
		Where("deleted_at = ?", 0).
		Order("sort_order ASC, created_at DESC").
		Find(&categories).Error
	if err != nil {
		log.Printf("Error querying categories: %v", err)
		return nil, err
	}
	return categories, nil
}

// GetCategoryByID 根据ID获取分类
func GetCategoryByID(id uint) (*models.Category, error) {
	var category models.Category
	err := config.DB.Model(&models.Category{}).
		Where("id = ? AND deleted_at = ?", id, 0).
		First(&category).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting category by ID: %v", err)
		return nil, err
	}
	return &category, nil
}

// CreateCategory 创建分类
func CreateCategory(category *models.Category) error {
	err := config.DB.Create(category).Error
	if err != nil {
		log.Printf("Error creating category: %v", err)
		return err
	}
	return nil
}

// UpdateCategory 更新分类
func UpdateCategory(category *models.Category) error {
	err := config.DB.Model(&models.Category{}).
		Where("id = ? AND deleted_at = ?", category.ID, 0).
		Updates(map[string]interface{}{
			"name":        category.Name,
			"slug":        category.Slug,
			"description": category.Description,
			"sort_order":  category.SortOrder,
			"updated_at":  time.Now().Unix(),
		}).Error
	if err != nil {
		log.Printf("Error updating category: %v", err)
		return err
	}
	return nil
}

// DeleteCategory 删除分类
func DeleteCategory(id uint) error {
	err := config.DB.Model(&models.Category{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting category: %v", err)
		return err
	}
	return nil
}

// BuildCategoryResponse 构建分类响应
func BuildCategoryResponse(category *models.Category) *models.CategoryResponse {
	return &models.CategoryResponse{
		ID:          category.ID,
		Name:        category.Name,
		Slug:        category.Slug,
		Description: category.Description,
		SortOrder:   category.SortOrder,
		CreatedAt:   formatTimestamp(category.CreatedAt),
		UpdatedAt:   formatTimestamp(category.UpdatedAt),
	}
}

// BuildCategoriesResponse 构建分类列表响应
func BuildCategoriesResponse(categories []models.Category) []models.CategoryResponse {
	responses := make([]models.CategoryResponse, 0, len(categories))
	for _, category := range categories {
		responses = append(responses, *BuildCategoryResponse(&category))
	}
	return responses
}
