package handlers

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

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

type PublicHandler struct {
	store *storage.ProductStore
}

func NewPublicHandler(store *storage.ProductStore) *PublicHandler {
	return &PublicHandler{store: store}
}

func (h *PublicHandler) ListProducts(c *gin.Context) {
	items, err := h.store.ListActive()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": sanitizeForPublic(items)})
}

func (h *PublicHandler) RecordProductView(c *gin.Context) {
	id := c.Param("id")
	fingerprint := buildViewerFingerprint(c)
	product, counted, err := h.store.IncrementView(id, fingerprint)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"id":        product.ID,
			"viewCount": product.ViewCount,
			"counted":   counted,
		},
	})
}

func buildViewerFingerprint(c *gin.Context) string {
	clientIP := strings.TrimSpace(c.ClientIP())
	userAgent := strings.TrimSpace(c.GetHeader("User-Agent"))
	language := strings.TrimSpace(c.GetHeader("Accept-Language"))
	return clientIP + "|" + userAgent + "|" + language
}

func sanitizeForPublic(items []models.Product) []models.Product {
	out := make([]models.Product, len(items))
	for i, item := range items {
		item.Codes = nil
		item.FixedContent = ""
		out[i] = item
	}
	return out
}

