package handlers

import (
	"fmt"
	"html/template"
	"log/slog"
	"net/http"

	"git.clustercockpit.org/moebiusband/go-http-skeleton/web"
	"github.com/olivere/vite"
)

func AdminHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		tpl := template.Must(template.ParseFS(web.Templates, "templates/admin.html", "templates/base.html"))
		viteFragment, err := vite.HTMLFragment(vite.Config{
			FS:    web.DistFS(),
			IsDev: false,
		})
		if err != nil {
			msg := fmt.Errorf("error instantiating vite fragment: %v", err)
			http.Error(w, msg.Error(), http.StatusInternalServerError)
			return
		}

		data := web.PageData{
			Title: "Admin",
			Vite:  viteFragment,
		}
		if err := tpl.ExecuteTemplate(w, "base", data); err != nil {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			slog.Error("Error executing template", "error", err)
		}
	}
}
