package auth

import (
	"errors"

	"github.com/gorilla/sessions"
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/v4"

	"github.com/rjNemo/rentease/internal/constant"
)

const (
	sessionName = "rentease"
	sessionAge  = 86400 * 7 // 7 days
)

type Service struct {
	secret      string
	admin       string
	adminSecret string
	apiKey      string
}

func NewService(secret, admin, adminSecret, apiKey string) (*Service, error) {
	if secret == "" || admin == "" || adminSecret == "" || apiKey == "" {
		return nil, errors.New("error building Auth service. Verify your env variables")
	}

	return &Service{
		secret,
		admin,
		adminSecret,
		apiKey,
	}, nil
}

func (as *Service) ValidCredentials(email, password string) bool {
	return email == as.admin && password == as.adminSecret
}

func (as *Service) ValidateApiKey(key string) bool {
	return key == as.apiKey
}

func (as *Service) getSession(c echo.Context) (*sessions.Session, error) {
	sess, err := session.Get(sessionName, c)
	if err != nil {
		return nil, err
	}

	sess.Options = &sessions.Options{
		Path:     constant.RouteLogin,
		MaxAge:   sessionAge,
		HttpOnly: true,
	}

	return sess, nil
}

func (as *Service) Authenticate(c echo.Context, key string) error {
	sess, err := as.getSession(c)
	if err != nil {
		return err
	}

	sess.Values["user"] = key
	return sess.Save(c.Request(), c.Response())
}

func (as *Service) Authenticated(c echo.Context) bool {
	sess, err := as.getSession(c)
	if err != nil {
		return false
	}

	user, ok := sess.Values["user"]
	return ok && user == "foo"
}
