package web

import (
	"net/http"
	"strings"

	"github.com/go-chi/chi"
	"github.com/go-chi/chi/middleware"
	"bitmask.me/skeleton/internal/app"
)

func registerRoutes(ac *app.App, r chi.Router) {
	h := NewHandlers(ac)

	r.Use(middleware.Recoverer)

	r.Route("/", func(r chi.Router) {
		r.Use(
			middleware.RedirectSlashes,
			h.Session().LoadAndSave,
		)

		r.Get("/", h.LandingPageHandler)

		r.Route("/app", func(r chi.Router) {
			// authenticated routes
			r.Use(requireLogin(h.Session()))

			r.Get("/", h.LandingPageHandler)
		})
	})

	r.Handle("/static/*", staticHandler(ac.Files, "/"))
}

// staticHandler handles the static assets path.
func staticHandler(fs http.FileSystem, prefix string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if prefix != "/" {
			r.URL.Path = strings.TrimPrefix(r.URL.Path, prefix)
		}
		http.FileServer(fs).ServeHTTP(w, r)
	}
}