package handler

import (
	"net/http"
	"strconv"

	"Engine/internal/model"
	"Engine/internal/service"
)

type VarianceHandler struct {
	svc *service.VarianceService
}

func NewVarianceHandler(svc *service.VarianceService) *VarianceHandler {
	return &VarianceHandler{svc: svc}
}

func (h *VarianceHandler) Report(w http.ResponseWriter, r *http.Request) {
	f := filterFromQuery(r)
	report, err := h.svc.Report(r.Context(), f)
	if err != nil {
		writeError(w, http.StatusInternalServerError, err.Error())
		return
	}
	writeJSON(w, http.StatusOK, report)
}

func (h *VarianceHandler) Alerts(w http.ResponseWriter, r *http.Request) {
	f := filterFromQuery(r)

	threshold := 10.0
	if t := r.URL.Query().Get("threshold"); t != "" {
		if v, err := strconv.ParseFloat(t, 64); err == nil {
			threshold = v
		}
	}

	alerts, err := h.svc.Alerts(r.Context(), f, threshold)
	if err != nil {
		writeError(w, http.StatusInternalServerError, err.Error())
		return
	}
	writeJSON(w, http.StatusOK, alerts)
}

func filterFromQuery(r *http.Request) service.VarianceFilter {
	q := r.URL.Query()

	year, _ := strconv.Atoi(q.Get("year"))
	period, _ := strconv.Atoi(q.Get("period"))

	version := model.BudgetVersion(q.Get("version"))
	if version == "" {
		version = model.VersionOriginal
	}

	return service.VarianceFilter{
		FiscalYear:   year,
		FiscalPeriod: period,
		DeptCode:     q.Get("dept"),
		Version:      version,
	}
}
