package handlers

import "net/http"

// Server-rendered page endpoints for the Phase F Appointments UI.
// HTML is generated at build time by frontend/build.ts; the per-page
// client TS bundles call /api/appointments* to populate the DOM and read
// id/project_id from window.location.

// handleAppointmentsListRedirect 301-redirects the legacy /appointments
// list URL to the canonical /events?type=appointment (t-paliad-115).
// Detail page /appointments/{id} stays type-specific. Drop this redirect
// once we're confident no caches / bookmarks / external links still hit
// the old URL.
func handleAppointmentsListRedirect(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "/events?type=appointment", http.StatusMovedPermanently)
}

func handleAppointmentsNewPage(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "dist/appointments-new.html")
}

func handleAppointmentsDetailPage(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "dist/appointments-detail.html")
}

// handleAppointmentsCalendarPage 301-redirects the legacy standalone
// calendar route to the canonical /events Kalender tab (t-paliad-224 /
// m/paliad#55). Counterpart of handleDeadlinesCalendarPage — same
// reasoning: the standalone page was orphaned in navigation since
// t-paliad-110, the canonical calendar lives inside /events.
func handleAppointmentsCalendarPage(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "/events?type=appointment&view=calendar", http.StatusMovedPermanently)
}

// handleSettingsPage serves the unified settings page with tabs for
// Profil / Benachrichtigungen / CalDAV. The active tab is picked
// client-side from ?tab=<name> so switching tabs doesn't round-trip.
func handleSettingsPage(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "dist/settings.html")
}

// settingsTabAliases maps every supported /settings/<slug> deep-link to its
// canonical ?tab=<name> value the client TS understands. Both the German tab
// IDs (profil/benachrichtigungen) and intuitive English aliases
// (profile/notifications) are accepted so bookmarks, smoke tests, and
// manually-typed URLs all land on the right tab.
var settingsTabAliases = map[string]string{
	"profil":             "profil",
	"profile":            "profil",
	"benachrichtigungen": "benachrichtigungen",
	"notifications":      "benachrichtigungen",
	"caldav":             "caldav",
}

// handleSettingsTabRedirect turns /settings/<slug> into /settings?tab=<canonical>
// as 301 Moved Permanently. Unknown slugs fall back to the bare /settings page
// (the client picks the default tab) so a typo doesn't 404.
func handleSettingsTabRedirect(w http.ResponseWriter, r *http.Request) {
	slug := r.PathValue("tab")
	canonical, ok := settingsTabAliases[slug]
	if !ok {
		http.Redirect(w, r, "/settings", http.StatusMovedPermanently)
		return
	}
	http.Redirect(w, r, "/settings?tab="+canonical, http.StatusMovedPermanently)
}
