package auth

import (
	"errors"
	"net/http"

	"github.com/gorilla/sessions"

	"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
	store       *sessions.CookieStore
}

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")
	}

	store := sessions.NewCookieStore([]byte(secret))
	store.Options = &sessions.Options{
		Path:     constant.RouteLogin,
		MaxAge:   sessionAge,
		HttpOnly: true,
	}

	return &Service{
		secret:      secret,
		admin:       admin,
		adminSecret: adminSecret,
		apiKey:      apiKey,
		store:       store,
	}, 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(r *http.Request) (*sessions.Session, error) {
	sess, err := as.store.Get(r, sessionName)
	if err != nil {
		return nil, err
	}

	return sess, nil
}

func (as *Service) Authenticate(w http.ResponseWriter, r *http.Request, key string) error {
	sess, err := as.getSession(r)
	if err != nil {
		return err
	}

	sess.Values["user"] = key
	return sess.Save(r, w)
}

func (as *Service) Authenticated(r *http.Request) bool {
	sess, err := as.getSession(r)
	if err != nil {
		return false
	}

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