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

// GetWorkByID 根据ID获取作品
func GetWorkByID(c *gin.Context) {
	id := c.Param("id")

	work, err := repositories.GetWorkByID(id)
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	if work == nil {
		utils.Error(c, 404, "Work not found")
		return
	}

	response, err := repositories.BuildWorkResponse(work)
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.Success(c, response)
}

// GetWorks 获取所有作品
func GetWorks(c *gin.Context) {
	works, err := repositories.GetWorks()
	if err != nil {
		utils.ServerError(c, err)
		return
	}

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

// AdminGetWorks 获取作品列表 (后台)
func AdminGetWorks(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

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

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

	utils.Success(c, res)
}

// AdminCreateWork 创建作品
func AdminCreateWork(c *gin.Context) {
	var work models.Work
	if err := c.ShouldBindJSON(&work); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

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

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

// AdminUpdateWork 更新作品
func AdminUpdateWork(c *gin.Context) {
	id := c.Param("id")

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

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

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

// AdminDeleteWork 删除作品
func AdminDeleteWork(c *gin.Context) {
	id := c.Param("id")

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

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