package server

import (
	"net/http"

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

func MakeAuthMiddleware(as *auth.Service) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.URL.Path == constant.RouteLogin {
				next.ServeHTTP(w, r)
				return
			}

			if !as.Authenticated(r) {
				http.Redirect(w, r, constant.RouteLogin, http.StatusSeeOther)
				return
			}

			next.ServeHTTP(w, r)
		})
	}
}
