package handlers

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	"mengyastore-backend/internal/auth"
	"mengyastore-backend/internal/storage"
)

type WishlistHandler struct {
	wishlistStore *storage.WishlistStore
	authClient    *auth.SproutGateClient
}

func NewWishlistHandler(wishlistStore *storage.WishlistStore, authClient *auth.SproutGateClient) *WishlistHandler {
	return &WishlistHandler{wishlistStore: wishlistStore, authClient: authClient}
}

func (h *WishlistHandler) requireUser(c *gin.Context) (string, bool) {
	authHeader := c.GetHeader("Authorization")
	if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
		return "", false
	}
	token := strings.TrimPrefix(authHeader, "Bearer ")
	result, err := h.authClient.VerifyToken(token)
	if err != nil || !result.Valid || result.User == nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期，请重新登录"})
		return "", false
	}
	return result.User.Account, true
}

func (h *WishlistHandler) GetWishlist(c *gin.Context) {
	account, ok := h.requireUser(c)
	if !ok {
		return
	}
	ids, err := h.wishlistStore.Get(account)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
}

type wishlistItemPayload struct {
	ProductID string `json:"productId"`
}

func (h *WishlistHandler) AddToWishlist(c *gin.Context) {
	account, ok := h.requireUser(c)
	if !ok {
		return
	}
	var payload wishlistItemPayload
	if err := c.ShouldBindJSON(&payload); err != nil || payload.ProductID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
		return
	}
	if err := h.wishlistStore.Add(account, payload.ProductID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	ids, _ := h.wishlistStore.Get(account)
	c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
}

func (h *WishlistHandler) RemoveFromWishlist(c *gin.Context) {
	account, ok := h.requireUser(c)
	if !ok {
		return
	}
	productID := c.Param("id")
	if productID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "缺少商品 ID"})
		return
	}
	if err := h.wishlistStore.Remove(account, productID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	ids, _ := h.wishlistStore.Get(account)
	c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
}
