package application

import (
	"errors"
	"net/http"

	"git.coopgo.io/coopgo-apps/parcoursmob/renderer"
	"git.coopgo.io/coopgo-apps/parcoursmob/services"
	"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
	cache "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
	"git.coopgo.io/coopgo-platform/emailing"
	"git.coopgo.io/coopgo-platform/groups-management/storage"
	"github.com/coreos/go-oidc"
	"github.com/spf13/viper"
)

type ApplicationHandler struct {
	config      *viper.Viper
	Renderer    *renderer.Renderer
	services    *services.ServicesHandler
	cache       cache.CacheHandler
	filestorage cache.FileStorage
	emailing    *emailing.Mailer
}

func NewApplicationHandler(cfg *viper.Viper, svc *services.ServicesHandler, cache cache.CacheHandler, filestorage cache.FileStorage, emailing *emailing.Mailer) (*ApplicationHandler, error) {
	templates_root := cfg.GetString("templates.root")
	renderer := renderer.NewRenderer(cfg, templates_root)
	return &ApplicationHandler{
		config:      cfg,
		Renderer:    renderer,
		services:    svc,
		cache:       cache,
		filestorage: filestorage,
		emailing:    emailing,
	}, nil
}

func (h *ApplicationHandler) NotFound(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNotFound)
}

func (h *ApplicationHandler) templateFile(file string) string {
	return h.config.GetString("templates.root") + file
}

func (h *ApplicationHandler) currentGroup(r *http.Request) (current_group storage.Group, err error) {
	g := r.Context().Value(identification.GroupKey)
	if g == nil {
		return storage.Group{}, errors.New("current group not found")
	}
	current_group = g.(storage.Group)

	return current_group, nil
}

func (h *ApplicationHandler) currentUser(r *http.Request) (current_user_token *oidc.IDToken, current_user_claims map[string]any, err error) {
	// Get current user ID
	u := r.Context().Value(identification.IdtokenKey)
	if u == nil {
		return nil, nil, errors.New("current user not found")
	}
	current_user_token = u.(*oidc.IDToken)

	// Get current user claims
	c := r.Context().Value(identification.ClaimsKey)
	if c == nil {
		return current_user_token, nil, errors.New("current user claims not found")
	}
	current_user_claims = c.(map[string]any)

	return current_user_token, current_user_claims, nil
}
