package server

import (
	"net/http"

	"github.com/labstack/echo/v4"

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

func handleLoginPage() echo.HandlerFunc {
	return func(c echo.Context) error {
		return renderTempl(c, http.StatusOK, view.Login(view.LoginFormViewModel{}))
	}
}

func handleLogin(as *auth.Service) echo.HandlerFunc {
	return func(c echo.Context) error {
		email := c.FormValue("email")
		password := c.FormValue("password")

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

		err := as.Authenticate(c, "foo")
		if err != nil {
			return err
		}

		return hxRedirect(c, http.StatusOK, constant.RouteBooking)
	}
}
