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

// GetSnippets 获取所有代码片段
func GetSnippets(c *gin.Context) {
	snippets, err := repositories.GetSnippets()
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	// 构建响应
	responses := repositories.BuildSnippetsResponse(snippets)
	if responses == nil {
		utils.Success(c, []interface{}{})
	} else {
		utils.Success(c, responses)
	}
}

func GetSnippet(c *gin.Context) {
	id := c.Param("id")
	// 从数据库获取代码片段
	snippet, err := repositories.GetSnippetByID(id)
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	if snippet == nil {
		utils.Error(c, 404, "Snippet not found")
		return
	}

	// 构建响应
	response := repositories.BuildSnippetResponse(snippet)

	utils.Success(c, response)
}

// AdminGetSnippets 获取代码片段列表 (后台)
func AdminGetSnippets(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

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

	list := repositories.BuildSnippetsResponse(snippets)
	res := gin.H{
		"list":  list,
		"total": total,
		"page":  page,
		"size":  pageSize,
	}
	if list == nil {
		res["list"] = []interface{}{}
	}

	utils.Success(c, res)
}

// AdminCreateSnippet 创建代码片段
func AdminCreateSnippet(c *gin.Context) {
	var snippet models.Snippet
	if err := c.ShouldBindJSON(&snippet); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

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

	utils.SuccessWithMsg(c, "Snippet created successfully", gin.H{"id": snippet.ID})
}

// AdminUpdateSnippet 更新代码片段
func AdminUpdateSnippet(c *gin.Context) {
	idStr := c.Param("id")

	var snippet models.Snippet
	if err := c.ShouldBindJSON(&snippet); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	snippet.ID = idStr

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

	utils.SuccessWithMsg(c, "Snippet updated successfully", nil)
}

// AdminDeleteSnippet 删除代码片段
func AdminDeleteSnippet(c *gin.Context) {
	idStr := c.Param("id")

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

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