package shared

import (
	"context"
	"git.markbailey.dev/cerbervs/ptpp/app/controller"
	"git.markbailey.dev/cerbervs/ptpp/app/session"
	"git.markbailey.dev/cerbervs/ptpp/lib/database"
	"git.markbailey.dev/cerbervs/ptpp/lib/logger"
	"git.markbailey.dev/cerbervs/ptpp/view/layout"
	"net/http"
	"os"

	"git.markbailey.dev/cerbervs/ptpp/view/homepage"
)

type HomePageHandler struct {
	controller.Controller
}

func (h HomePageHandler) Init(s session.IManager, d database.IDB, l logger.ILogger) error {
	h.Logger = l
	h.Db = d
	h.Session = s

	return nil
}

func (h HomePageHandler) Get(w http.ResponseWriter, r *http.Request) error {
	if r.URL.Path != "/" {
		w.WriteHeader(http.StatusNotFound)
		err := layout.NotFound().Render(context.Background(), w)
		if err != nil {
			h.Logger.Error(h.Logger.Wrap(err, "Error rendering 404 page"))
			return err
		}
		return nil
	}

	if err := homepage.Homepage(os.Getenv("$HTMX_APP_ENV")).Render(context.Background(), w); err != nil {
		h.Logger.Error(h.Logger.Wrap(err, "Error rendering homepage"))
		return err
	}

	return nil
}
