package router

import (
	"github.com/gorilla/sessions"
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/v4"
	"net/http"

	"git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config"
)

const (
	sessionName = `session`
	sessionKey  = `login`
)

func login(c echo.Context) error {
	pass := c.FormValue("password")

	if config.GetAdminPassword() != pass {
		return echo.NewHTTPError(http.StatusBadRequest, "Wrong password.")
	}

	sess, _ := session.Get(sessionName, c)
	sess.Options = &sessions.Options{
		MaxAge: 86400 * 7,
	}
	sess.Values[sessionKey] = true
	err := sess.Save(c.Request(), c.Response())
	if err != nil {
		return echo.ErrInternalServerError
	}

	if c.QueryParam("direct") == "true" {
		return c.Redirect(http.StatusSeeOther, "/admin")
	}

	return c.NoContent(http.StatusOK)
}
