package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"mengyastore-backend/internal/storage"
)

type StatsHandler struct {
	orderStore *storage.OrderStore
	siteStore  *storage.SiteStore
}

func NewStatsHandler(orderStore *storage.OrderStore, siteStore *storage.SiteStore) *StatsHandler {
	return &StatsHandler{orderStore: orderStore, siteStore: siteStore}
}

// GetStats 订单总数与站点访问总数。
// @Summary 站点统计
// @Tags 公开
// @Produce json
// @Success 200 {object} SwaggerStatsWrap
// @Failure 500 {object} SwaggerErrorBody
// @Router /api/stats [get]
func (h *StatsHandler) GetStats(c *gin.Context) {
	totalOrders, err := h.orderStore.Count()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	totalVisits, err := h.siteStore.GetTotalVisits()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"totalOrders": totalOrders,
			"totalVisits": totalVisits,
		},
	})
}

// RecordVisit 记录一次站点访问并返回累计访问量。
// @Summary 记录站点访问
// @Tags 公开
// @Produce json
// @Success 200 {object} SwaggerVisitWrap
// @Failure 500 {object} SwaggerErrorBody
// @Router /api/site/visit [post]
func (h *StatsHandler) RecordVisit(c *gin.Context) {
	fingerprint := buildViewerFingerprint(c)
	totalVisits, counted, err := h.siteStore.RecordVisit(fingerprint)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"totalVisits": totalVisits,
			"counted":     counted,
		},
	})
}

// GetMaintenance 当前维护模式与原因。
// @Summary 维护模式状态
// @Tags 公开
// @Produce json
// @Success 200 {object} SwaggerMaintenanceWrap
// @Failure 500 {object} SwaggerErrorBody
// @Router /api/site/maintenance [get]
func (h *StatsHandler) GetMaintenance(c *gin.Context) {
	enabled, reason, err := h.siteStore.GetMaintenance()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"maintenance": enabled,
			"reason":      reason,
		},
	})
}
