package main

import (
	"log"
	"net/http"

	"github.com/redis/go-redis/v9"
)

func BasicAuth(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		user, pass, ok := r.BasicAuth()
		if !ok || user != adminUser || pass != adminPass {
			w.Header().Set("WWW-Authenticate", `Basic realm="Lehrerzimmer"`)
			http.Error(w, "Unauthorized", 401)
			return
		}
		next(w, r)
	}
}

func main() {
	redisAddr := getEnv("REDIS_ADDR", "localhost:6379")
	adminUser = getEnv("ADMIN_USER", "lehrer")
	adminPass = getEnv("ADMIN_PASS", "geheim123")

	rdb = redis.NewClient(&redis.Options{Addr: redisAddr})
	if _, err := rdb.Ping(ctx).Result(); err != nil {
		log.Fatal("Redis:", err)
	}

	initGameConfig()
	initBadWords()

	fs := http.FileServer(http.Dir("./static"))
	http.Handle("/", fs)

	http.HandleFunc("/api/config", Logger(handleConfig))
	http.HandleFunc("/api/start", Logger(handleStart))
	http.HandleFunc("/api/validate", Logger(handleValidate))
	http.HandleFunc("/ws", handleWebSocket)
	http.HandleFunc("/api/submit-name", Logger(handleSubmitName))
	http.HandleFunc("/api/leaderboard", Logger(handleLeaderboard))
	http.HandleFunc("/api/claim/delete", Logger(handleClaimDelete))

	http.HandleFunc("/admin", Logger(BasicAuth(handleAdminPage)))
	http.HandleFunc("/api/admin/badwords", Logger(BasicAuth(handleAdminBadwords)))
	http.HandleFunc("/api/admin/list", Logger(BasicAuth(handleAdminList)))
	http.HandleFunc("/api/admin/action", Logger(BasicAuth(handleAdminAction)))
	http.HandleFunc("/api/admin/chunks", Logger(BasicAuth(handleAdminChunks)))
	http.HandleFunc("/api/admin/upload", Logger(BasicAuth(handleAdminUpload)))
	http.HandleFunc("/api/admin/save-config", Logger(BasicAuth(handleAdminSaveConfig)))
	http.HandleFunc("/admin/assets", Logger(BasicAuth(func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "./secure/assets.html")
	})))
	http.HandleFunc("/admin/editor", Logger(BasicAuth(handleEditorPage)))
	http.HandleFunc("/admin/obstacle_editor", Logger(BasicAuth(handleObstacleEditorPage)))

	log.Println("🦖 Server läuft auf :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
