package rootmux

import (
	"net/http"
	"os"

	"forge.grandlyon.com/web-et-numerique/llle_project/backoffice-server/internal/auth"
	"forge.grandlyon.com/web-et-numerique/llle_project/backoffice-server/internal/common"
	"forge.grandlyon.com/web-et-numerique/llle_project/backoffice-server/internal/monthlyNews"
	"github.com/nicolaspernoud/vestibule/pkg/middlewares"
)

type RootMux struct {
	Mux     http.Handler
	Manager *auth.Manager
}

func CreateRootMux(staticDir string) RootMux {

	mainMux := http.NewServeMux()
	m := auth.NewManager()

	mainMux.HandleFunc("/OAuth2Login", m.HandleOAuth2Login)
	mainMux.Handle("/OAuth2Callback", m.HandleOAuth2Callback())
	mainMux.HandleFunc("/Logout", m.HandleLogout)
	mainMux.Handle("/api/common/WhoAmI", auth.ValidateAuthMiddleware(auth.WhoAmI(), []string{"*"}, false))

	adminMux := http.NewServeMux()
	adminMux.HandleFunc("/monthlyNews/", monthlyNews.ProcessMonthlyNews)
	mainMux.Handle("/api/admin/", http.StripPrefix("/api/admin", auth.ValidateAuthMiddleware(adminMux, []string{os.Getenv("ADMIN_ROLE")}, true)))

	// Serve static files falling back to serving index.html
	mainMux.Handle("/", middlewares.NoCache(http.FileServer(&common.FallBackWrapper{Assets: http.Dir(staticDir)})))

	return RootMux{mainMux, &m}
}