package handlers

import (
	"errors"
	"net/http"
	"time"

	"mgit.msbls.de/m/paliad/internal/services"
)

// GET /api/tools/fristenrechner/follow-ups — given a trigger event and
// a trigger date, return the immediate follow-up sequencing rules with
// their computed due dates (Fristenrechner overhaul S1, design §6.2).
//
// Query params:
//   event         - procedural_events.code OR procedural_events.id
//                   (uuid) OR sequencing_rules.id (uuid). Required.
//   trigger_date  - YYYY-MM-DD. Defaults to today when omitted, so the
//                   frontend can show a result preview before the user
//                   commits a date.
//   party         - "claimant" | "defendant" | "court" | "both".
//                   Optional; narrows follow-ups by primary_party
//                   (claimant/defendant filters keep "both" rules
//                   visible — they're bilateral procedural moves).
//   court_id      - paliad.courts.id (uuid); selects the holiday
//                   calendar for date adjustment. Optional.
func handleFristenrechnerFollowUps(w http.ResponseWriter, r *http.Request) {
	if dbSvc == nil || dbSvc.fristenrechner == nil {
		writeJSON(w, http.StatusServiceUnavailable, map[string]string{
			"error": "Fristenrechner ist vorübergehend nicht verfügbar (keine Datenbank).",
		})
		return
	}
	q := r.URL.Query()
	eventRef := q.Get("event")
	if eventRef == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{
			"error": "event ist erforderlich (procedural_events.code oder id)",
		})
		return
	}
	triggerDate := q.Get("trigger_date")
	if triggerDate == "" {
		triggerDate = time.Now().Format("2006-01-02")
	}

	resp, err := dbSvc.fristenrechner.LookupFollowUps(
		r.Context(),
		eventRef,
		triggerDate,
		q.Get("party"),
		q.Get("court_id"),
	)
	if err != nil {
		if errors.Is(err, services.ErrUnknownProceduralEvent) {
			writeJSON(w, http.StatusNotFound, map[string]string{
				"error": "Unbekanntes Ereignis: " + eventRef,
			})
			return
		}
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, resp)
}
