package server

import (
	"net/http"

	httputil "git.mstar.dev/mstar/goutils/http"
	"github.com/rs/zerolog/hlog"

	"git.mstar.dev/mstar/linstrom/storage"
)

func placeholderEndpoint(w http.ResponseWriter, r *http.Request) {
	hlog.FromRequest(r).Error().Stringer("url", r.URL).Msg("Placeholder endpoint accessed")
	httputil.HttpErr(
		w,
		HttpErrIdPlaceholder,
		"Endpoint not implemented yet, this is a placeholder",
		http.StatusInternalServerError,
	)
}

func StorageFromRequest(r *http.Request) *storage.Storage {
	store, ok := r.Context().Value(ContextKeyStorage).(*storage.Storage)
	if !ok {
		hlog.FromRequest(r).Fatal().Msg("Failed to get storage reference from context")
		return nil
	}
	return store
}

func ActorIdFromRequest(r *http.Request) (string, bool) {
	id, ok := r.Context().Value(ContextKeyActorId).(string)
	return id, ok
}

func NoteIdFromRequest(r *http.Request) string {
	return r.PathValue("noteId")
}

func AccountIdFromRequest(r *http.Request) string {
	return r.PathValue("accountId")
}

func CheckIfAccountIdHasPermissions(accId string, perms storage.Role, store *storage.Storage) bool {
	acc, err := store.FindAccountById(accId)
	if err != nil {
		return false
	}
	roles, err := store.FindRolesByNames(acc.Roles)
	if err != nil {
		return false
	}
	collapsed := storage.CollapseRolesIntoOne(roles...)
	return storage.CompareRoles(&collapsed, &perms)
}
