package web

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

// Every page the casino routes to must be in the games template set. This is not
// a fussy test: uno shipped with its handler wired, its engine tested and its
// template written, and every visit to the table answered "unknown page" with a
// 500 — because the page was never added to the list server.go parses. Nothing
// else caught it, since the other tests call the handlers straight and never go
// through render(). Add a game, add it here.
func TestEveryCasinoPageRenders(t *testing.T) {
	s := newCasino(t)

	pages := []string{
		"/games",
		"/games/blackjack",
		"/games/hangman",
		"/games/solitaire",
		"/games/trivia",
		"/games/uno",
		"/games/holdem",
	}

	mux := http.NewServeMux()
	s.casinoRoutes(mux)

	for _, path := range pages {
		t.Run(path, func(t *testing.T) {
			w := httptest.NewRecorder()
			mux.ServeHTTP(w, as(t, s, "reala", "GET", path, nil))

			if w.Code != http.StatusOK {
				t.Fatalf("GET %s = %d, want 200 (body: %s)", path, w.Code, strings.TrimSpace(w.Body.String()))
			}
			// render() writes the 500 as a body and a page that fails halfway
			// through still comes back 200, so look at what was actually served.
			body := w.Body.String()
			if strings.Contains(body, "unknown page") {
				t.Fatalf("GET %s served the unknown-page error: the template is missing from the games set in server.go", path)
			}
			if !strings.Contains(body, "</html>") {
				t.Fatalf("GET %s did not render a whole page (%d bytes) — the template blew up mid-render", path, len(body))
			}
		})
	}
}
