package controller

import (
	"strconv"

	"github.com/QuantumNous/new-api/common"
	"github.com/QuantumNous/new-api/model"

	"github.com/gin-gonic/gin"
)

// GetAllPricingTags 获取所有定价标签
func GetAllPricingTags(c *gin.Context) {
	list, err := model.GetAllPricingTags()
	if err != nil {
		common.ApiError(c, err)
		return
	}
	common.ApiSuccess(c, list)
}

// CreatePricingTagRequest 创建定价标签请求
type CreatePricingTagRequest struct {
	Name        string `json:"name" binding:"required"`
	Color       string `json:"color"`
	Description string `json:"description"`
	SortOrder   int    `json:"sort_order"`
}

// CreatePricingTag 创建定价标签
func CreatePricingTag(c *gin.Context) {
	var req CreatePricingTagRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		common.ApiError(c, err)
		return
	}

	// 检查名称是否重复
	existing, _ := model.GetPricingTagByName(req.Name)
	if existing != nil {
		common.ApiErrorMsg(c, "tag name already exists")
		return
	}

	pt := &model.PricingTag{
		Name:        req.Name,
		Color:       req.Color,
		Description: req.Description,
		SortOrder:   req.SortOrder,
	}
	if pt.Color == "" {
		pt.Color = "#1890ff"
	}
	if err := pt.Insert(); err != nil {
		common.ApiError(c, err)
		return
	}

	common.ApiSuccess(c, pt)
}

// UpdatePricingTagRequest 更新定价标签请求
type UpdatePricingTagRequest struct {
	Name        string `json:"name"`
	Color       string `json:"color"`
	Description string `json:"description"`
	SortOrder   int    `json:"sort_order"`
}

// UpdatePricingTag 更新定价标签
func UpdatePricingTag(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		common.ApiError(c, err)
		return
	}

	var req UpdatePricingTagRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		common.ApiError(c, err)
		return
	}

	pt, err := model.GetPricingTagById(id)
	if err != nil {
		common.ApiError(c, err)
		return
	}

	// 检查名称是否与其他标签重复
	if req.Name != "" && req.Name != pt.Name {
		existing, _ := model.GetPricingTagByName(req.Name)
		if existing != nil && existing.Id != id {
			common.ApiErrorMsg(c, "tag name already exists")
			return
		}
		pt.Name = req.Name
	}

	if req.Color != "" {
		pt.Color = req.Color
	}
	pt.Description = req.Description
	pt.SortOrder = req.SortOrder

	if err := pt.Update(); err != nil {
		common.ApiError(c, err)
		return
	}

	common.ApiSuccess(c, pt)
}

// DeletePricingTag 删除定价标签
func DeletePricingTag(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		common.ApiError(c, err)
		return
	}

	pt := &model.PricingTag{Id: id}
	if err := pt.Delete(); err != nil {
		common.ApiError(c, err)
		return
	}

	common.ApiSuccess(c, nil)
}
