package auth

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

	mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
	ma "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
)

func (h *AuthHandler) Onboarding(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	key := r.FormValue("key")
	onboarding, err := h.cache.Get("onboarding/" + key)
	if err != nil {
		fmt.Println(err)
		h.Renderer.AuthOnboardingKO(w, r, key)
		return
	}

	onboardingmap := onboarding.(map[string]any)

	if r.Method == "POST" {
		if r.FormValue("password") == "" {
			fmt.Println("password is empty !")
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

		groups := []string{
			onboardingmap["group"].(string),
			//onboardingmap["group"].(string) + ":admin",
		}

		if onboardingmap["admin"].(bool) {
			groups = append(groups, onboardingmap["group"].(string)+":admin")
		}
		display_name := fmt.Sprint(r.FormValue("first_name")) + " " + fmt.Sprint(r.FormValue("last_name"))
		account := &ma.Account{
			Authentication: ma.AccountAuth{
				Local: ma.LocalAuth{
					Username: onboardingmap["username"].(string),
					Password: r.FormValue("password"),
				},
			},
			Namespace: "parcoursmob",

			Data: map[string]any{
				"display_name": display_name,
				"first_name":   r.FormValue("first_name"),
				"last_name":    r.FormValue("last_name"),
				"email":        onboardingmap["username"],
				"groups":       groups,
			},
		}

		acc, err := mobilityaccounts.AccountFromStorageType(account)
		if err != nil {
			fmt.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

		request := &mobilityaccounts.RegisterRequest{
			Account: acc,
		}

		_, err = h.services.GRPC.MobilityAccounts.Register(context.TODO(), request)

		if err != nil {
			fmt.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

		err = h.cache.Delete("onboarding/" + key)
		if err != nil {
			fmt.Println(err)
		}

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

	h.Renderer.AuthOnboarding(w, r, key, onboarding)
}
