package admin

import (
	"net/http"
	"strconv"

	"bindbox-game/internal/code"
	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/validation"
	prodsvc "bindbox-game/internal/service/product"
)

type createProductCategoryRequest struct {
	Name     string `json:"name" binding:"required"`
	ParentID int64  `json:"parent_id"`
	Status   int32  `json:"status"`
}

type createProductCategoryResponse struct {
	ID      int64  `json:"id"`
	Message string `json:"message"`
}

// CreateProductCategory 创建商品分类
// @Summary 创建商品分类
// @Tags 管理端.商品
// @Accept json
// @Produce json
// @Param RequestBody body createProductCategoryRequest true "请求参数"
// @Success 200 {object} createProductCategoryResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/product_categories [post]
// @Security LoginVerifyToken
func (h *handler) CreateProductCategory() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createProductCategoryRequest)
		res := new(createProductCategoryResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		if ctx.SessionUserInfo().IsSuper != 1 {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.CreateAdminError, "禁止操作"))
			return
		}
		item, err := h.product.CreateCategory(ctx.RequestContext(), prodsvc.CreateCategoryInput{
			Name: req.Name, ParentID: req.ParentID, Status: req.Status,
		})
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.CreateAdminError, err.Error()))
			return
		}
		res.ID = item.ID
		res.Message = "操作成功"
		ctx.Payload(res)
	}
}

type modifyProductCategoryRequest struct {
	Name     *string `json:"name"`
	ParentID *int64  `json:"parent_id"`
	Status   *int32  `json:"status"`
}

type pcSimpleMessage struct {
	Message string `json:"message"`
}

// ModifyProductCategory 修改商品分类
// @Summary 修改商品分类
// @Tags 管理端.商品
// @Accept json
// @Produce json
// @Param category_id path string true "分类ID"
// @Param RequestBody body modifyProductCategoryRequest true "请求参数"
// @Success 200 {object} pcSimpleMessage
// @Failure 400 {object} code.Failure
// @Router /api/admin/product_categories/{category_id} [put]
// @Security LoginVerifyToken
func (h *handler) ModifyProductCategory() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(modifyProductCategoryRequest)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		idStr := ctx.Param("category_id")
		id, _ := strconv.ParseInt(idStr, 10, 64)
		if ctx.SessionUserInfo().IsSuper != 1 {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.CreateAdminError, "禁止操作"))
			return
		}
		if err := h.product.ModifyCategory(ctx.RequestContext(), id, prodsvc.ModifyCategoryInput{Name: req.Name, ParentID: req.ParentID, Status: req.Status}); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.CreateAdminError, err.Error()))
			return
		}
		ctx.Payload(pcSimpleMessage{Message: "操作成功"})
	}
}

// DeleteProductCategory 删除商品分类
// @Summary 删除商品分类
// @Tags 管理端.商品
// @Accept json
// @Produce json
// @Param category_id path string true "分类ID"
// @Success 200 {object} pcSimpleMessage
// @Failure 400 {object} code.Failure
// @Router /api/admin/product_categories/{category_id} [delete]
// @Security LoginVerifyToken
func (h *handler) DeleteProductCategory() core.HandlerFunc {
	return func(ctx core.Context) {
		idStr := ctx.Param("category_id")
		id, _ := strconv.ParseInt(idStr, 10, 64)
		if ctx.SessionUserInfo().IsSuper != 1 {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.CreateAdminError, "禁止操作"))
			return
		}
		if err := h.product.DeleteCategory(ctx.RequestContext(), id); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.CreateAdminError, err.Error()))
			return
		}
		ctx.Payload(pcSimpleMessage{Message: "操作成功"})
	}
}

type listProductCategoriesRequest struct {
	Name     string `form:"name"`
	Status   *int32 `form:"status"`
	Page     int    `form:"page"`
	PageSize int    `form:"page_size"`
}

type productCategoryListItem struct {
	ID       int64  `json:"id"`
	Name     string `json:"name"`
	ParentID int64  `json:"parent_id"`
	Status   int32  `json:"status"`
}
type listProductCategoriesResponse struct {
	Page     int                       `json:"page"`
	PageSize int                       `json:"page_size"`
	Total    int64                     `json:"total"`
	List     []productCategoryListItem `json:"list"`
}

// ListProductCategories 查看商品分类列表
// @Summary 查看商品分类列表
// @Tags 管理端.商品
// @Accept json
// @Produce json
// @Param name query string false "名称"
// @Param status query int false "状态"
// @Param page query int true "页码" default(1)
// @Param page_size query int true "每页数量" default(20)
// @Success 200 {object} listProductCategoriesResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/product_categories [get]
// @Security LoginVerifyToken
func (h *handler) ListProductCategories() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(listProductCategoriesRequest)
		res := new(listProductCategoriesResponse)
		if err := ctx.ShouldBindForm(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		items, total, err := h.product.ListCategories(ctx.RequestContext(), prodsvc.ListCategoriesInput{Name: req.Name, Status: req.Status, Page: req.Page, PageSize: req.PageSize})
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.CreateAdminError, err.Error()))
			return
		}
		res.Page = req.Page
		res.PageSize = req.PageSize
		res.Total = total
		res.List = make([]productCategoryListItem, len(items))
		for i, it := range items {
			res.List[i] = productCategoryListItem{ID: it.ID, Name: it.Name, ParentID: it.ParentID, Status: it.Status}
		}
		ctx.Payload(res)
	}
}
