package dashboard

import (
	"strconv"

	"github.com/gin-gonic/gin"
	"hyapp-admin-server/internal/config"
	"hyapp-admin-server/internal/repository"
	"hyapp-admin-server/internal/response"
)

type Handler struct {
	service *DashboardService
}

func New(store *repository.Store, cfg config.Config) *Handler {
	return &Handler{service: NewService(store, cfg)}
}

func (h *Handler) DashboardOverview(c *gin.Context) {
	overview, err := h.service.Overview()
	if err != nil {
		response.ServerError(c, "获取总览失败")
		return
	}
	response.OK(c, overview)
}

func (h *Handler) StatisticsOverview(c *gin.Context) {
	overview, err := h.service.StatisticsOverview(c.Request.Context(), StatisticsQuery{
		AppCode:       c.DefaultQuery("app_code", "lalu"),
		StartMS:       parseInt64(c.Query("start_ms")),
		EndMS:         parseInt64(c.Query("end_ms")),
		SeriesStartMS: parseInt64(c.Query("series_start_ms")),
		SeriesEndMS:   parseInt64(c.Query("series_end_ms")),
		RegionID:      parseInt64(c.Query("region_id")),
		CountryID:     parseInt64(c.Query("country_id")),
	})
	if err != nil {
		response.ServerError(c, "获取统计总览失败")
		return
	}
	response.OK(c, overview)
}

func parseInt64(value string) int64 {
	parsed, _ := strconv.ParseInt(value, 10, 64)
	return parsed
}
