package handlers

import (
	"net/http"
	"strconv"

	"sale/internal/models"
	"sale/internal/schemas"
	"sale/internal/utils"

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

type PurchaseGroupHandler struct{}

func NewPurchaseGroupHandler() *PurchaseGroupHandler {
	return &PurchaseGroupHandler{}
}

func (h *PurchaseGroupHandler) List(c *gin.Context) {
	var groups []models.PurchaseGroup
	utils.DB.Order("sort_order ASC, id ASC").Preload("Categories").Find(&groups)
	c.JSON(http.StatusOK, gin.H{"data": groups})
}

func (h *PurchaseGroupHandler) Create(c *gin.Context) {
	var req schemas.CreatePurchaseGroupRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var existing models.PurchaseGroup
	if err := utils.DB.Where("name = ?", req.Name).First(&existing).Error; err == nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "分组名称已存在"})
		return
	}

	group := models.PurchaseGroup{
		Name:        req.Name,
		Description: req.Description,
		SortOrder:   req.SortOrder,
	}

	if err := utils.DB.Create(&group).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create purchase group"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"data": group})
}

func (h *PurchaseGroupHandler) Update(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	var group models.PurchaseGroup
	if err := utils.DB.First(&group, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Purchase group not found"})
		return
	}

	var req schemas.UpdatePurchaseGroupRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if req.Name != nil && *req.Name != group.Name {
		var existing models.PurchaseGroup
		if err := utils.DB.Where("name = ? AND id != ?", *req.Name, id).First(&existing).Error; err == nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "分组名称已存在"})
			return
		}
	}

	updates := make(map[string]interface{})
	if req.Name != nil {
		updates["name"] = *req.Name
	}
	if req.Description != nil {
		updates["description"] = *req.Description
	}
	if req.SortOrder != nil {
		updates["sort_order"] = *req.SortOrder
	}

	utils.DB.Model(&group).Updates(updates)
	c.JSON(http.StatusOK, gin.H{"data": group})
}

func (h *PurchaseGroupHandler) Delete(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))

	var categoryCount int64
	utils.DB.Model(&models.Category{}).Where("purchase_group_id = ?", id).Count(&categoryCount)
	if categoryCount > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "该分组下有分类，无法删除"})
		return
	}

	if err := utils.DB.Delete(&models.PurchaseGroup{}, id).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete purchase group"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "Purchase group deleted successfully"})
}