package authentication

import (
	"errors"
	"net/http"

	"git.kirsle.net/apps/gophertype/pkg/console"
	"git.kirsle.net/apps/gophertype/pkg/models"
	"git.kirsle.net/apps/gophertype/pkg/session"
)

// CurrentUser returns the currently logged-in user in the browser session.
func CurrentUser(r *http.Request) (models.User, error) {
	sess := session.Get(r)
	if sess.LoggedIn {
		id := sess.UserID
		user, err := models.Users.GetUserByID(id)
		if err != nil {
			console.Error("CurrentUser: user '%d' was not found in DB! Logging out the session", id)
			sess.LoggedIn = false
			sess.UserID = 0
			return user, err
		}
		return user, err
	}
	return models.User{}, errors.New("not logged in")
}

// Login logs the browser session in as the user.
func Login(w http.ResponseWriter, r *http.Request, user models.User) {
	sess := session.Get(r)

	sess.LoggedIn = true
	sess.UserID = user.ID
	sess.Save(w)
}

// Logout logs the current user out.
func Logout(w http.ResponseWriter, r *http.Request) {
	sess := session.Get(r)
	sess.LoggedIn = false
	sess.UserID = 0
	sess.Save(w)
}

// LoggedIn returns whether the session is logged in as a user.
func LoggedIn(r *http.Request) bool {
	sess := session.Get(r)
	return sess.LoggedIn
}
