package handlers

import (
	"net/http"
	"strings"
)

// registerLegacyRedirects wires every historical German URL path to its
// English successor as a 301 Moved Permanently. One entry per legacy prefix;
// sub-paths are preserved verbatim in the redirect target (e.g.
// /akten/abc/deadlines → /projects/abc/deadlines).
//
// Only GET is redirected — old POST/PATCH/DELETE API endpoints are not
// mirrored. API clients must update to the English /api/* paths.
func registerLegacyRedirects(mux *http.ServeMux) {
	// Prefix pairs: when the request path starts with key, it's rewritten to
	// value + whatever followed the key. Order does not matter because each
	// prefix is registered as its own pattern on the mux.
	prefixes := map[string]string{
		"/akten":         "/projects",
		"/projekte":      "/projects",
		"/fristen":       "/deadlines",
		"/termine":       "/appointments",
		"/notizen":       "/notes",
		"/einstellungen": "/settings",
		"/checklisten":   "/checklists",
		"/dezernate":     "/admin/partner-units",
		"/departments":   "/admin/partner-units",
		"/parteien":      "/parties",
		"/gerichte":      "/courts",
		"/glossar":       "/glossary",
		// Memorable aliases — sidebar uses the canonical path but users
		// type these from memory and would otherwise hit the 404 chrome.
		"/whatsnew":      "/changelog",
	}
	for oldPrefix, newPrefix := range prefixes {
		mux.Handle("GET "+oldPrefix, redirectPrefix(oldPrefix, newPrefix))
		mux.Handle("GET "+oldPrefix+"/", redirectPrefix(oldPrefix, newPrefix))
	}

	// In-path aliases: redirect parameterised legacy URLs whose alias sits
	// between path segments rather than at the prefix. The canonical project
	// children tab is /projects/{id}/children; bookmarks to the older
	// /sub-projects suffix would otherwise hit the 404 chrome.
	mux.Handle("GET /projects/{id}/sub-projects", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		target := "/projects/" + r.PathValue("id") + "/children"
		if r.URL.RawQuery != "" {
			target += "?" + r.URL.RawQuery
		}
		http.Redirect(w, r, target, http.StatusMovedPermanently)
	}))
}

func redirectPrefix(oldPrefix, newPrefix string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tail := strings.TrimPrefix(r.URL.Path, oldPrefix)
		target := newPrefix + tail
		if r.URL.RawQuery != "" {
			target += "?" + r.URL.RawQuery
		}
		http.Redirect(w, r, target, http.StatusMovedPermanently)
	})
}
