package handler

import (
	"fmt"
	"net/http"
	"time"

	"nex/backend/internal/service"

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

// StatsHandler 统计处理器
type StatsHandler struct {
	statsService service.StatsService
}

// NewStatsHandler 创建统计处理器
func NewStatsHandler(statsService service.StatsService) *StatsHandler {
	return &StatsHandler{statsService: statsService}
}

// GetStats 查询统计
func (h *StatsHandler) GetStats(c *gin.Context) {
	providerID := c.Query("provider_id")
	modelName := c.Query("model_name")

	startDate, err := parseDateParam(c, "start_date")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	endDate, err := parseDateParam(c, "end_date")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	stats, err := h.statsService.Get(providerID, modelName, startDate, endDate)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "查询统计失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, stats)
}

// AggregateStats 聚合统计
func (h *StatsHandler) AggregateStats(c *gin.Context) {
	providerID := c.Query("provider_id")
	modelName := c.Query("model_name")
	groupBy := c.Query("group_by")

	startDate, err := parseDateParam(c, "start_date")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	endDate, err := parseDateParam(c, "end_date")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	stats, err := h.statsService.Get(providerID, modelName, startDate, endDate)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "查询统计失败: " + err.Error(),
		})
		return
	}

	result := h.statsService.Aggregate(stats, groupBy)
	c.JSON(http.StatusOK, result)
}

// parseDateParam 解析日期查询参数
func parseDateParam(c *gin.Context, paramName string) (*time.Time, error) {
	dateStr := c.Query(paramName)
	if dateStr == "" {
		return nil, nil
	}
	t, err := time.Parse("2006-01-02", dateStr)
	if err != nil {
		return nil, fmt.Errorf("无效的 %s 格式，应为 YYYY-MM-DD", paramName)
	}
	return &t, nil
}
