// backend/routes.go
package main

import (
	"embed"
	"io/fs"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/prometheus/client_golang/prometheus/promhttp"

	"scm.bstein.dev/bstein/Pegasus/backend/internal"
)

//go:embed web/dist
var webFS embed.FS

func buildRouter(um *internal.UserMap, jf jellyfinClient) http.Handler {
	r := chi.NewRouter()
	r.Use(corsForTus)

	r.Get("/healthz", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok"))
	})
	r.Get("/version", func(w http.ResponseWriter, _ *http.Request) {
		writeJSON(w, map[string]any{
			"version":  version,
			"git":      git,
			"built_at": builtAt,
		})
	})

	r.Post("/api/login", loginHandler(um, jf))
	r.Post("/api/logout", logoutHandler())
	r.Get("/api/whoami", whoamiHandler(um))
	r.Get("/api/list", listHandler(um))
	r.Post("/api/rename", renameHandler(um, jf))
	r.Delete("/api/file", deleteHandler(um, jf))
	r.Post("/api/mkdir", mkdirHandler(um, jf))

	tusHandler := newTusHandler(um, jf)
	r.Route("/tus", func(rt chi.Router) {
		rt.Use(sessionRequired)
		rt.Post("/", tusHandler.PostFile)
		rt.Head("/{id}", tusHandler.HeadFile)
		rt.Patch("/{id}", tusHandler.PatchFile)
		rt.Delete("/{id}", tusHandler.DelFile)
		rt.Get("/{id}", tusHandler.GetFile)
	})

	r.Handle("/metrics", promhttp.Handler())

	appFS, err := fs.Sub(webFS, "web/dist")
	if err == nil {
		static := http.FileServer(http.FS(appFS))
		r.Get("/", func(w http.ResponseWriter, r *http.Request) {
			static.ServeHTTP(w, r)
		})
		r.Method("GET", "/*", http.StripPrefix("/", static))
	}

	r.Get("/debug/env", debugEnvHandler())
	r.Get("/debug/write-test", debugWriteTestHandler(um))

	r.NotFound(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "no route for "+r.Method+" "+r.URL.Path, http.StatusNotFound)
	})

	return debugHandler(r)
}
