package handlers

import (
	"net/http"
	"sale/internal/models"
	"sale/internal/utils"

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

type BrandHandler struct{}

func NewBrandHandler() *BrandHandler {
	return &BrandHandler{}
}

func (h *BrandHandler) List(c *gin.Context) {
	var brands []models.Brand
	utils.DB.Where("deleted_at IS NULL").Order("sort_order ASC, name ASC").Find(&brands)
	c.JSON(http.StatusOK, gin.H{"data": brands})
}

func (h *BrandHandler) Create(c *gin.Context) {
	var brand models.Brand
	if err := c.ShouldBindJSON(&brand); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	utils.DB.Create(&brand)
	c.JSON(http.StatusOK, gin.H{"data": brand})
}

func (h *BrandHandler) Update(c *gin.Context) {
	id := c.Param("id")
	var brand models.Brand
	if err := utils.DB.First(&brand, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Brand not found"})
		return
	}
	var req struct {
		Name      *string `json:"name"`
		Icon      *string `json:"icon"`
		Info      *string `json:"info"`
		SortOrder *int    `json:"sort_order"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	updates := make(map[string]interface{})
	if req.Name != nil {
		updates["name"] = *req.Name
	}
	if req.Icon != nil {
		updates["icon"] = *req.Icon
	}
	if req.Info != nil {
		updates["info"] = *req.Info
	}
	if req.SortOrder != nil {
		updates["sort_order"] = *req.SortOrder
	}
	utils.DB.Model(&brand).Updates(updates)
	utils.DB.First(&brand, brand.ID)
	c.JSON(http.StatusOK, gin.H{"data": brand})
}

func (h *BrandHandler) Delete(c *gin.Context) {
	id := c.Param("id")
	utils.DB.Delete(&models.Brand{}, id)
	c.JSON(http.StatusOK, gin.H{"message": "Brand deleted"})
}
