package auth

import (
	"net/http"

	"github.com/gorilla/sessions"
)

// SessionName is the cookie name for authenticated sessions.
const SessionName = "ww_session"

// Store is the signed + encrypted cookie store, initialised by InitSessionStore.
var Store *sessions.CookieStore

// InitSessionStore creates the cookie store with the server secret.
func InitSessionStore(secret string) {
	Store = sessions.NewCookieStore([]byte(secret))
	Store.Options = &sessions.Options{
		Path:     "/",
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
		MaxAge:   30 * 24 * 3600, // 30 days
	}
}

// GetUserID returns the authenticated user id from the request, if any.
func GetUserID(r *http.Request) (int64, bool) {
	if Store == nil {
		return 0, false
	}
	s, err := Store.Get(r, SessionName)
	if err != nil {
		return 0, false
	}
	id, ok := s.Values["user_id"].(int64)
	return id, ok
}

// SetUserID records the user id in the session cookie.
func SetUserID(w http.ResponseWriter, r *http.Request, id int64) error {
	s, _ := Store.Get(r, SessionName)
	s.Values["user_id"] = id
	return s.Save(r, w)
}

// Clear destroys the session (logout).
func Clear(w http.ResponseWriter, r *http.Request) error {
	s, _ := Store.Get(r, SessionName)
	s.Options.MaxAge = -1
	return s.Save(r, w)
}
