package admin

import (
	"context"
	"errors"
	"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"

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

type IndexHandler struct {
	controller.Controller
}

func (h IndexHandler) Init(s session.IManager, d database.IDB, l logger.ILogger, ctx controller.IControllerCtx) controller.IController {
	h.Logger = l
	h.Db = d
	h.Session = s
	h.Ctx = ctx

	return h
}

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

	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
}
