package service

import (
	"errors"
	"strconv"

	baseCnf "git.ego.freeddns.org/egommerce/go-api-pkg/config"
	"github.com/gofiber/fiber/v2"
)

var (
	AuthService *Auth
	JWTService  *JWT

	ErrLoginIncorrect = errors.New("login incorrect")
)

func init() {
	cookieExpireTime, _ := strconv.Atoi(baseCnf.GetEnv("AUTH_COOKIE_EXPIRE_TIME", "5"))
	AuthService = &Auth{"jwt_token", "jwt_token_refresh", cookieExpireTime}
}

type Auth struct {
	TokenCookieName        string
	RefreshTokenCookieName string
	cookieExpireTime       int
}

func (a *Auth) Login(login, pass string) (string, error) {
	if login == "admin" && pass == "secret" {
		token, err := JWTService.CreateToken()
		if err != nil {
			return "", err
		}

		return token, nil
	}

	return "", ErrLoginIncorrect
}

// Cookie create fiber.Cookie struct
func (a *Auth) Cookie(name, value string) *fiber.Cookie {
	return &fiber.Cookie{
		Name:   name,
		Value:  value,
		MaxAge: a.cookieExpireTime * 300, // FIXME: env/config
		Path:   "/",                      // FIXME: env/config
	}
}
