package auth

import (
	"context"
	"fmt"
	"net/http"

	groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
)

func (h *AuthHandler) Groups(w http.ResponseWriter, r *http.Request) {
	session, _ := h.idp.SessionsStore.Get(r, "parcoursmob_session")

	if r.Method == "POST" {
		r.ParseForm()

		groupid := r.FormValue("group")

		session.Values["organization"] = groupid
		session.Save(r, w)

		http.Redirect(w, r, "/app/", http.StatusFound)

		return
	}

	tokenstring, ok := session.Values["idtoken"]

	if !ok {
		http.Redirect(w, r, "/app/", http.StatusFound)
		return
	}

	idtoken, err := h.idp.TokenVerifier.Verify(context.Background(), tokenstring.(string))
	if err != nil {
		delete(session.Values, "idtoken")
		http.Redirect(w, r, "/app/", http.StatusFound)
		return
	}

	var claims map[string]any

	err = idtoken.Claims(&claims)
	if err != nil {
		fmt.Println(err)
	}

	g := claims["groups"]

	groups_interface, ok := g.([]any)
	if !ok {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	groups := []string{}

	for _, v := range groups_interface {
		groups = append(groups, v.(string))
	}

	request := &groupsmanagement.GetGroupsBatchRequest{
		Groupids: groups,
	}

	resp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), request)
	if err != nil {
		fmt.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	var groupsresponse = []any{}

	for _, group := range resp.Groups {
		if group.Namespace != "parcoursmob_organizations" {
			continue
		}
		g := group.ToStorageType()
		groupsresponse = append(groupsresponse, g)
	}

	h.Renderer.AuthGroups(w, r, groupsresponse)
}

func (h *AuthHandler) GroupSwitch(w http.ResponseWriter, r *http.Request) {
	session, _ := h.idp.SessionsStore.Get(r, "parcoursmob_session")
	delete(session.Values, "organization")
	session.Save(r, w)
	http.Redirect(w, r, "/app/", http.StatusFound)
}
