package gophertype

import (
	"net/http"

	"git.kirsle.net/apps/gophertype/pkg/controllers"
	"git.kirsle.net/apps/gophertype/pkg/middleware"
	"git.kirsle.net/apps/gophertype/pkg/models"
)

// SetupRouter sets up the HTTP router.
func (s *Site) SetupRouter() error {
	router := http.NewServeMux()

	router.HandleFunc("/", controllers.CatchAllHandler)
	router.HandleFunc("/age-verify", controllers.AgeVerify)
	router.HandleFunc("/login", controllers.Login)
	router.HandleFunc("GET /logout", controllers.Logout)
	router.HandleFunc("/comments", controllers.PostComment)
	router.HandleFunc("/comments/subscription", controllers.ManageSubscription)
	router.HandleFunc("/comments/quick-delete", controllers.CommentQuickDelete)
	router.HandleFunc("/contact", controllers.ContactHandler)
	router.HandleFunc("GET /blog", controllers.BlogIndex(models.Public, false))
	router.HandleFunc("GET /tagged", controllers.TagIndex)
	router.HandleFunc("GET /tagged/{tag}", controllers.BlogIndex(models.Public, true))
	router.HandleFunc("GET /archive", controllers.BlogArchive)
	router.HandleFunc("GET /blog/random", controllers.BlogRandom)
	router.HandleFunc("/ask", controllers.QuestionHandler)
	router.HandleFunc("GET /blog.rss", controllers.RSSFeed)
	router.HandleFunc("GET /blog.atom", controllers.RSSFeed)
	router.HandleFunc("GET /blog.json", controllers.RSSFeed)
	router.HandleFunc("GET /blog/search", controllers.BlogSearch)

	// Initial setup page
	router.Handle("/admin/setup", middleware.ExampleMiddleware(http.HandlerFunc(controllers.InitialSetup)))

	// Login Required
	router.HandleFunc("/admin", controllers.AdminIndex)
	router.HandleFunc("/admin/users", controllers.AdminIndex)
	router.Handle("GET /blog/drafts", middleware.LoginRequired(controllers.BlogIndex(models.Draft, false)))
	router.Handle("GET /blog/private", middleware.LoginRequired(controllers.BlogIndex(models.Private, false)))
	router.Handle("GET /blog/unlisted", middleware.LoginRequired(controllers.BlogIndex(models.Unlisted, false)))
	router.Handle("/blog/edit", middleware.LoginRequired(http.HandlerFunc(controllers.EditPost)))
	router.Handle("/ask/answer", middleware.LoginRequired(http.HandlerFunc(controllers.AnswerHandler)))
	router.Handle("/admin/upload", middleware.LoginRequired(http.HandlerFunc(controllers.UploadHandler)))

	// Global middlewares.
	var (
		withCSRF           = middleware.CSRF(router)
		withSession        = middleware.Session(withCSRF)
		withAuthentication = middleware.Authentication(withSession)
		withAgeGate        = middleware.AgeGate(withAuthentication)
		withRecovery       = middleware.Recovery(withAgeGate)
		withLogger         = middleware.Logging(withRecovery)
	)

	s.mux = withLogger

	return nil
}
