// Filename: internal/handlers/dashboard_handler.go
package handlers

import (
	"gemini-balancer/internal/errors"
	"gemini-balancer/internal/service"
	"net/http"
	"strconv"

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

// DashboardHandler 负责处理全局仪表盘相关的API请求
type DashboardHandler struct {
	queryService *service.DashboardQueryService
}

func NewDashboardHandler(qs *service.DashboardQueryService) *DashboardHandler {
	return &DashboardHandler{queryService: qs}
}

// GetOverview 获取仪表盘的全局统计卡片数据
func (h *DashboardHandler) GetOverview(c *gin.Context) {
	stats, err := h.queryService.GetDashboardOverviewData()
	if err != nil {
		apiErr := errors.NewAPIError(errors.ErrInternalServer, err.Error())
		c.JSON(apiErr.HTTPStatus, apiErr)
		return
	}
	c.JSON(http.StatusOK, stats)
}

// GetChart
func (h *DashboardHandler) GetChart(c *gin.Context) {
	var groupID *uint
	if groupIDStr := c.Query("groupId"); groupIDStr != "" {
		if id, err := strconv.Atoi(groupIDStr); err == nil {
			uid := uint(id)
			groupID = &uid
		}
	}

	chartData, err := h.queryService.QueryHistoricalChart(c.Request.Context(), groupID)
	if err != nil {
		apiErr := errors.NewAPIError(errors.ErrDatabase, err.Error())
		c.JSON(apiErr.HTTPStatus, apiErr)
		return
	}
	c.JSON(http.StatusOK, chartData)
}

// GetRequestStats
func (h *DashboardHandler) GetRequestStats(c *gin.Context) {
	period := c.Param("period")
	stats, err := h.queryService.GetRequestStatsForPeriod(c.Request.Context(), period)
	if err != nil {
		apiErr := errors.NewAPIError(errors.ErrBadRequest, err.Error())
		c.JSON(apiErr.HTTPStatus, apiErr)
		return
	}
	c.JSON(http.StatusOK, stats)
}
