package auth

import (
	"context"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io"
	"net/http"
	"time"

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

func (h *AuthHandler) LostPasswordInit(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		r.ParseForm()
		email := r.FormValue("email")
		if email != "" {
			account, err := h.services.GRPC.MobilityAccounts.GetAccountUsername(context.TODO(), &grpcapi.GetAccountUsernameRequest{
				Username:  email,
				Namespace: "parcoursmob",
			})
			if err != nil {
				fmt.Println(err)
				http.Redirect(w, r, "/app/", http.StatusFound)
				return
			}

			b := make([]byte, 16)
			if _, err := io.ReadFull(rand.Reader, b); err != nil {
				fmt.Println(err)
				w.WriteHeader(http.StatusInternalServerError)
				return
			}
			key := base64.RawURLEncoding.EncodeToString(b)

			passwordretrieval := map[string]any{
				"username":   email,
				"account_id": account.Account.Id,
				"key":        key,
			}

			h.cache.PutWithTTL("retrieve-password/"+key, passwordretrieval, 72*time.Hour)

			if err := h.emailing.Send("auth.retrieve_password", email, passwordretrieval); err != nil {
				fmt.Println(err)
				w.WriteHeader(http.StatusInternalServerError)
				return
			}

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

}

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

	key := r.FormValue("key")
	recover, err := h.cache.Get("retrieve-password/" + key)
	if err != nil {
		fmt.Println(err)
		h.Renderer.LostPasswordRecoverKO(w, r, key)
		return
	}

	if r.Method == "POST" {
		newpassword := r.FormValue("password")
		if newpassword == "" {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("Password is empty"))
			return
		}

		_, err := h.services.GRPC.MobilityAccounts.ChangePassword(context.TODO(), &grpcapi.ChangePasswordRequest{
			Id:       recover.(map[string]any)["account_id"].(string),
			Password: newpassword,
		})

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

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

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

	}
	h.Renderer.LostPasswordRecover(w, r, recover)
}
