package handlers

import (
	"net/http"

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

// CalDAVHandler handles CalDAV sync HTTP endpoints.
type CalDAVHandler struct {
	svc *services.CalDAVService
}

// NewCalDAVHandler creates a new CalDAV handler.
func NewCalDAVHandler(svc *services.CalDAVService) *CalDAVHandler {
	return &CalDAVHandler{svc: svc}
}

// TriggerSync handles POST /api/caldav/sync — triggers a full sync for the current tenant.
func (h *CalDAVHandler) TriggerSync(w http.ResponseWriter, r *http.Request) {
	tenantID, ok := auth.TenantFromContext(r.Context())
	if !ok {
		writeError(w, http.StatusUnauthorized, "no tenant context")
		return
	}

	cfg, err := h.svc.LoadTenantConfig(tenantID)
	if err != nil {
		writeError(w, http.StatusBadRequest, "CalDAV not configured for this tenant")
		return
	}

	status, err := h.svc.SyncTenant(r.Context(), tenantID, *cfg)
	if err != nil {
		// Still return the status — it contains partial results + error info
		writeJSON(w, http.StatusOK, map[string]any{
			"status": "completed_with_errors",
			"sync":   status,
		})
		return
	}

	writeJSON(w, http.StatusOK, map[string]any{
		"status": "ok",
		"sync":   status,
	})
}

// GetStatus handles GET /api/caldav/status — returns last sync status.
func (h *CalDAVHandler) GetStatus(w http.ResponseWriter, r *http.Request) {
	tenantID, ok := auth.TenantFromContext(r.Context())
	if !ok {
		writeError(w, http.StatusUnauthorized, "no tenant context")
		return
	}

	status := h.svc.GetStatus(tenantID)
	if status == nil {
		writeJSON(w, http.StatusOK, map[string]any{
			"status":       "no_sync_yet",
			"last_sync_at": nil,
		})
		return
	}

	writeJSON(w, http.StatusOK, status)
}
