package handlers

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

	"crowdsec-dashy/internal/crowdsec"
)

// MetricsHandler serves the parsed cscli metrics page.
type MetricsHandler struct {
	deps Deps
}

func NewMetricsHandler(deps Deps) *MetricsHandler {
	return &MetricsHandler{deps: deps}
}

// MetricsData is passed to the metrics template.
type MetricsData struct {
	PageData
	Sections []crowdsec.MetricsSection
}

func (h *MetricsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	pd := NewPageData(r, "Metrics", h.deps.CLIAvailable, h.deps.PollInterval)

	var sections []crowdsec.MetricsSection
	if h.deps.CLIAvailable {
		ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
		defer cancel()
		var err error
		sections, err = h.deps.CLI.GetMetrics(ctx)
		if err != nil {
			pd.Flash = FlashMessage{Type: "error", Message: fmt.Sprintf("cscli error: %v", err)}
		}
	}

	h.deps.Renderer.Render(w, "metrics", MetricsData{PageData: pd, Sections: sections})
}
