package server

import (
	"net/http"

	"github.com/rjNemo/rentease/internal/constant"
	"github.com/rjNemo/rentease/internal/service/auth"
	"github.com/rjNemo/rentease/internal/view"
)

func handleLoginPage() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := renderTempl(w, http.StatusOK, view.Login(view.LoginFormViewModel{})); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}

func handleLogin(as *auth.Service) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		email := r.FormValue("email")
		password := r.FormValue("password")

		if !as.ValidCredentials(email, password) {
			lfvm := view.LoginFormViewModel{
				Email:    email,
				Password: password,
				Errors:   make(map[string]string),
			}
			lfvm.Errors["credentials"] = "invalid credentials"
			if err := renderTempl(w, http.StatusUnauthorized, view.LoginForm(lfvm)); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
			return
		}

		if err := as.Authenticate(w, r, "foo"); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		if err := hxRedirect(w, http.StatusOK, constant.RouteBooking); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}
