package Auth

import (
	"log"
	"net/http"
	"time"

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Database"
)

// Logout logs out from system
func Logout(w http.ResponseWriter, r *http.Request) {
	var (
		c            *http.Cookie
		sessionToken string
		err          error
	)

	c, err = r.Cookie("session_token")
	if err != nil {
		if err == http.ErrNoCookie {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	sessionToken = c.Value

	err = Database.DeleteSessionByID(sessionToken)
	if err != nil {
		log.Println("Could not delete session cookie")
	}

	http.SetCookie(w, &http.Cookie{
		Name:    "session_token",
		Value:   "",
		Expires: time.Now(),
	})

	w.WriteHeader(http.StatusOK)
}
