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

func parseSnippetID(c *gin.Context) (uint, bool) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil || id == 0 {
		utils.Error(c, 400, "Invalid snippet ID")
		return 0, false
	}
	return uint(id), true
}

type snippetPayload struct {
	Title       string `json:"title"`
	Code        string `json:"code"`
	Type        string `json:"type"`
	CodeTypeID  uint   `json:"codeTypeId"`
	Description string `json:"description"`
	PostIDs     []uint `json:"postIds"`
}

func (p *snippetPayload) toSnippet(id uint) models.Snippet {
	return models.Snippet{
		ID:          id,
		Title:       p.Title,
		Code:        p.Code,
		Type:        p.Type,
		CodeTypeID:  p.CodeTypeID,
		Description: p.Description,
	}
}

// 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, ok := parseSnippetID(c)
	if !ok {
		return
	}

	snippet, err := repositories.GetSnippetByID(id)
	if err != nil {
		utils.ServerError(c, err)
		return
	}

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

	utils.Success(c, repositories.BuildSnippetResponse(snippet))
}

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

	filter := repositories.AdminSnippetFilter{
		Keyword: c.Query("keyword"),
	}
	if typeIDStr := c.Query("codeTypeId"); typeIDStr != "" {
		if id, err := strconv.ParseUint(typeIDStr, 10, 32); err == nil {
			filter.CodeTypeID = uint(id)
		}
	}

	snippets, total, err := repositories.GetAdminSnippets(page, pageSize, filter)
	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 payload snippetPayload
	if err := c.ShouldBindJSON(&payload); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	snippet := payload.toSnippet(0)
	syncSnippetTypeFromCodeType(&snippet)

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

	if err := repositories.ReplaceSnippetPosts(snippet.ID, payload.PostIDs); err != nil {
		utils.ServerError(c, err)
		return
	}

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

// AdminUpdateSnippet 更新代码片段
func AdminUpdateSnippet(c *gin.Context) {
	id, ok := parseSnippetID(c)
	if !ok {
		return
	}

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

	snippet := payload.toSnippet(id)
	syncSnippetTypeFromCodeType(&snippet)

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

	if err := repositories.ReplaceSnippetPosts(snippet.ID, payload.PostIDs); err != nil {
		utils.ServerError(c, err)
		return
	}

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

func syncSnippetTypeFromCodeType(snippet *models.Snippet) {
	if snippet.CodeTypeID == 0 {
		return
	}
	ct, err := repositories.GetCodeTypeByID(snippet.CodeTypeID)
	if err == nil && ct != nil {
		snippet.Type = ct.Name
	}
}

// AdminDeleteSnippet 删除代码片段
func AdminDeleteSnippet(c *gin.Context) {
	id, ok := parseSnippetID(c)
	if !ok {
		return
	}

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

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