package handlers

import (
	"encoding/json"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/user/nanometrics/server/db"
)

func MetricsHistoryHandler(database *db.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
		if len(parts) < 4 {
			http.Error(w, "invalid path", 400)
			return
		}
		agentID := parts[2]

		now := time.Now().Unix()
		from := now - 3600
		to := now

		if v := r.URL.Query().Get("from"); v != "" {
			if n, err := strconv.ParseInt(v, 10, 64); err == nil {
				from = n
			}
		}
		if v := r.URL.Query().Get("to"); v != "" {
			if n, err := strconv.ParseInt(v, 10, 64); err == nil {
				to = n
			}
		}

		history, err := database.GetMetricsHistory(agentID, from, to)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(history)
	}
}
