package handlers

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

	"crowdsec-dashy/internal/crowdsec"
)

// DashboardHandler serves the main dashboard page.
type DashboardHandler struct {
	deps Deps
}

func NewDashboardHandler(deps Deps) *DashboardHandler {
	return &DashboardHandler{deps: deps}
}

// DashboardData is passed to the dashboard template.
type DashboardData struct {
	PageData
	RecentDecisions []crowdsec.Decision
	RecentAlerts    []crowdsec.Alert
	LAPIHealthy     bool
}

func (h *DashboardHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
	defer cancel()

	decisions, _ := h.deps.LAPI.ListDecisions(ctx, crowdsec.DecisionFilter{Limit: 10})
	alerts, _ := h.deps.LAPI.ListAlerts(ctx, crowdsec.AlertFilter{Limit: 10})

	h.deps.Renderer.Render(w, "dashboard", DashboardData{
		PageData:        NewPageData(r, "Dashboard", h.deps.CLIAvailable, h.deps.PollInterval),
		RecentDecisions: decisions,
		RecentAlerts:    alerts,
		LAPIHealthy:     h.deps.LAPI.IsHealthy(ctx),
	})
}
