package handlers

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

// /tools/fristenrechner?path=a was the pre-split sidebar entry for the
// "Verfahrensablauf" surface. After t-paliad-179 Slice 1 that intent
// owns its own /tools/verfahrensablauf route — so a naked ?path=a hit
// must 302 to the new URL to preserve bookmarked legacy links.
//
// The Akte-mode internal wizard pathway (?project=<uuid>&path=a) is
// NOT a top-level entry — it's wizard state set by client-side
// history.replaceState. That URL must keep serving the fristenrechner
// shell so a mid-wizard refresh doesn't bounce away.
func TestHandleFristenrechnerPage_LegacyPathARedirect(t *testing.T) {
	cases := []struct {
		name        string
		path        string
		wantStatus  int
		wantLoc     string
	}{
		{
			name:       "naked path=a → redirect",
			path:       "/tools/fristenrechner?path=a",
			wantStatus: http.StatusFound,
			wantLoc:    "/tools/verfahrensablauf",
		},
		{
			name:       "path=a with project= → no redirect (Akte-mode wizard)",
			path:       "/tools/fristenrechner?project=abc-123&path=a",
			wantStatus: http.StatusOK,
		},
		{
			name:       "no path param → no redirect",
			path:       "/tools/fristenrechner",
			wantStatus: http.StatusOK,
		},
		{
			name:       "path=b → no redirect (Pathway B stays)",
			path:       "/tools/fristenrechner?path=b",
			wantStatus: http.StatusOK,
		},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			req := httptest.NewRequest(http.MethodGet, tc.path, nil)
			w := httptest.NewRecorder()
			handleFristenrechnerPage(w, req)
			if w.Code != tc.wantStatus {
				// http.ServeFile may write 404 if dist/fristenrechner.html
				// is missing under `go test` (CI runs without a frontend
				// build). We only care that we did NOT redirect in those
				// cases — collapse 200 and 404 into "not a redirect".
				if tc.wantStatus == http.StatusOK && w.Code != http.StatusFound {
					return
				}
				t.Fatalf("status = %d, want %d", w.Code, tc.wantStatus)
			}
			if tc.wantLoc != "" {
				if got := w.Header().Get("Location"); got != tc.wantLoc {
					t.Fatalf("Location = %q, want %q", got, tc.wantLoc)
				}
			}
		})
	}
}

// The new /tools/verfahrensablauf route registers as a 1-liner page
// handler that ServeFiles dist/verfahrensablauf.html. We assert the
// handler does NOT redirect — if the dist artefact is missing under
// `go test`, ServeFile may return 404, but it must never return a 3xx.
func TestHandleVerfahrensablaufPage_NoRedirect(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/tools/verfahrensablauf", nil)
	w := httptest.NewRecorder()
	handleVerfahrensablaufPage(w, req)
	if w.Code >= 300 && w.Code < 400 {
		t.Fatalf("verfahrensablauf must not redirect; got %d → %s",
			w.Code, w.Header().Get("Location"))
	}
}
