package initialize

import (
	"net/http"

	"git.schreifuchs.ch/schreifuchs/ng-blog/internal/auth"
	"git.schreifuchs.ch/schreifuchs/ng-blog/internal/config"
	"git.schreifuchs.ch/schreifuchs/ng-blog/internal/model"
	"git.schreifuchs.ch/schreifuchs/ng-blog/internal/posts"
	"git.schreifuchs.ch/schreifuchs/ng-blog/pkg/cors"
	"git.schreifuchs.ch/schreifuchs/ng-blog/pkg/middlewares"
	"git.schreifuchs.ch/schreifuchs/ng-blog/web"
	"github.com/gorilla/mux"
)

// CreateMux creates and configures a mux router with authentication and post-related routes.
func CreateMux(cfg *config.Config) (r *mux.Router) {
	r = mux.NewRouter()
	r.Use(cors.HandlerForOrigin("*"))

	app(r.PathPrefix("/api").Subrouter(), cfg)

	frontend := web.Frontend
	r.PathPrefix("/").Handler(middlewares.AddPrefix("/dist/frontend/browser", http.FileServerFS(frontend)))

	r.Methods("OPTIONS").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// The CORS middleware should set up the headers for you
		w.WriteHeader(http.StatusNoContent)
	})

	return
}

func app(r *mux.Router, cfg *config.Config) {
	db := model.Init()
	blg := posts.New(db)
	auth := auth.New(&cfg.Auth, db)

	// auth
	r.HandleFunc("/login", auth.Login).Methods("POST")
	r.HandleFunc("/signup", auth.Signup).Methods("POST")
	r.Handle("/logout", auth.Authenticated(auth.Logout)).Methods("DELETE")

	// Posts
	r.Handle("/posts", auth.Authenticated(blg.SavePost, model.RoleUser, model.RoleAdmin)).Methods("POST")
	r.Handle("/posts", auth.Authenticated(blg.SavePost, model.RoleUser, model.RoleAdmin)).Methods("PUT")
	r.Handle("/posts/{postID}", auth.Authenticated(blg.DeletePost, model.RoleUser, model.RoleAdmin)).Methods("DELETE")
	r.Handle("/posts", http.HandlerFunc(blg.GetAllPosts)).Methods("GET")
}
