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"
)

// GetCategories 获取所有分类
func GetCategories(c *gin.Context) {
	categories, err := repositories.GetCategories()
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	utils.Success(c, repositories.BuildCategoriesResponse(categories))
}

// GetCategoryByID 根据ID获取分类
func GetCategoryByID(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		utils.Error(c, 400, "Invalid category ID")
		return
	}

	category, err := repositories.GetCategoryByID(uint(id))
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	if category == nil {
		utils.Error(c, 404, "Category not found")
		return
	}

	utils.Success(c, repositories.BuildCategoryResponse(category))
}

// AdminCreateCategory 创建分类
func AdminCreateCategory(c *gin.Context) {
	var category models.Category
	if err := c.ShouldBindJSON(&category); err != nil {
		utils.Error(c, 400, err.Error())
		return
	}

	if err := repositories.CreateCategory(&category); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.Success(c, repositories.BuildCategoryResponse(&category))
}

// AdminUpdateCategory 更新分类
func AdminUpdateCategory(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		utils.Error(c, 400, "Invalid category ID")
		return
	}

	var category models.Category
	if err := c.ShouldBindJSON(&category); err != nil {
		utils.Error(c, 400, err.Error())
		return
	}
	category.ID = uint(id)

	if err := repositories.UpdateCategory(&category); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.Success(c, repositories.BuildCategoryResponse(&category))
}

// AdminDeleteCategory 删除分类
func AdminDeleteCategory(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		utils.Error(c, 400, "Invalid category ID")
		return
	}

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

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