package handlers

import (
	"net/http"
	"strconv"

	"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
)

// DeadlineRuleHandlers holds handlers for deadline rule endpoints
type DeadlineRuleHandlers struct {
	rules *services.DeadlineRuleService
}

// NewDeadlineRuleHandlers creates deadline rule handlers
func NewDeadlineRuleHandlers(rs *services.DeadlineRuleService) *DeadlineRuleHandlers {
	return &DeadlineRuleHandlers{rules: rs}
}

// List handles GET /api/deadline-rules
// Query params: proceeding_type_id (optional int filter)
func (h *DeadlineRuleHandlers) List(w http.ResponseWriter, r *http.Request) {
	var proceedingTypeID *int
	if v := r.URL.Query().Get("proceeding_type_id"); v != "" {
		id, err := strconv.Atoi(v)
		if err != nil {
			writeError(w, http.StatusBadRequest, "invalid proceeding_type_id")
			return
		}
		proceedingTypeID = &id
	}

	rules, err := h.rules.List(proceedingTypeID)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "failed to list deadline rules")
		return
	}

	writeJSON(w, http.StatusOK, rules)
}

// ListProceedingTypes handles GET /api/proceeding-types
func (h *DeadlineRuleHandlers) ListProceedingTypes(w http.ResponseWriter, r *http.Request) {
	types, err := h.rules.ListProceedingTypes()
	if err != nil {
		writeError(w, http.StatusInternalServerError, "failed to list proceeding types")
		return
	}

	writeJSON(w, http.StatusOK, types)
}

// GetRuleTree handles GET /api/deadline-rules/{type}
// {type} is the proceeding type code (e.g., "INF", "REV")
func (h *DeadlineRuleHandlers) GetRuleTree(w http.ResponseWriter, r *http.Request) {
	typeCode := r.PathValue("type")
	if typeCode == "" {
		writeError(w, http.StatusBadRequest, "proceeding type code required")
		return
	}

	tree, err := h.rules.GetRuleTree(typeCode)
	if err != nil {
		writeError(w, http.StatusNotFound, "proceeding type not found")
		return
	}

	writeJSON(w, http.StatusOK, tree)
}
