package handlers

import (
	"context"
	"git.markbailey.dev/cervers/ptpp/view/layout"
	"net/http"
	"os"

	"git.markbailey.dev/cervers/ptpp/lib/logger"
	"git.markbailey.dev/cervers/ptpp/view/homepage"
)

type HomePageHandler struct {
	logger logger.ILogger
}

func NewHomePageHandler(l logger.ILogger) *HomePageHandler {
	return &HomePageHandler{
		logger: l,
	}
}

func (h HomePageHandler) Homepage(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
}
