package handlers

import (
	"log"
	"net/http"

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

// gateOnboarded wraps a page handler so that an authenticated user who has
// not yet filled in paliad.users is redirected to /onboarding instead of
// landing on a page that will silently return empty data.
//
// Scope: matter-management pages (Dashboard, Akten, Deadlines, Appointments,
// CalDAV settings). The knowledge-platform pages (Kostenrechner, Glossar,
// Links, Downloads, Gerichte, Gebührentabellen, Checklisten, Fristenrechner)
// work without a paliad.users row and are deliberately NOT gated.
//
// The gate is a no-op when:
//   - The DB is not configured (no services available → no row to check).
//   - No user id is in context (will have been 302'd to /login already).
//   - The lookup errors (we log, then fall through so a DB blip doesn't
//     lock users out of pages that can render a graceful error instead).
func gateOnboarded(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if dbSvc == nil {
			h(w, r)
			return
		}
		uid, ok := auth.UserIDFromContext(r.Context())
		if !ok {
			h(w, r)
			return
		}
		u, err := dbSvc.users.GetByID(r.Context(), uid)
		if err != nil {
			log.Printf("onboarding gate: lookup failed for %s: %v", uid, err)
			h(w, r)
			return
		}
		if u == nil {
			http.Redirect(w, r, "/onboarding", http.StatusFound)
			return
		}
		h(w, r)
	}
}
