package admin

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

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

type IndexHandler struct {
	logger  logger.ILogger
	session session.IManager
}

func NewAdminIndexHandler(l logger.ILogger, s session.IManager) *IndexHandler {
	return &IndexHandler{
		logger:  l,
		session: s,
	}
}

func (h IndexHandler) Index(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
	}

	username, ok := r.Context().Value("username").(string)
	if !ok {
		err := errors.New("cannot decode request context: for key \"username\"")
		h.logger.Error(h.logger.Wrap(err, "Error decoding request context"))
		return err
	}

	if err := admin.Index(username).Render(context.Background(), w); err != nil {
		h.logger.Error(h.logger.Wrap(err, "Error rendering admin index page"))
		return err
	}

	return nil
}
