package middleware

import (
	"context"
	"net/http"

	"git.kirsle.net/apps/gophertype/pkg/authentication"
	"git.kirsle.net/apps/gophertype/pkg/session"
)

// LoginRequired is a middleware for authenticated endpoints.
func LoginRequired(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, err := authentication.CurrentUser(r)
		if err != nil {
			// Redirect to the login page.
			w.Header().Set("Location", "/login?next="+r.URL.Path)
			w.WriteHeader(http.StatusFound)
			return
		}

		next.ServeHTTP(w, r)
	})
}

// Authentication checks the authentication and loads the user onto the request context.
func Authentication(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, err := authentication.CurrentUser(r)
		if err != nil {
			// User not logged in, go to next middleware.
			next.ServeHTTP(w, r)
			return
		}

		// Put the CurrentUser into the request context.
		ctx := context.WithValue(r.Context(), session.CurrentUserKey, user)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
