package auxhttp

import (
	"errors"
	"fmt"
	"strings"
)

func GetBearerToken(authHeader string) (string, error) {
	var err error
	var res string

	const bearerKey = "Bearer"
	const numWords = 2

	authData := strings.SplitN(authHeader, " ", numWords)
	if len(authData) < numWords {
		err = errors.New("Authorization key and value not found")
		return res, err
	}

	authKey := strings.TrimSpace(authData[0])
	if authKey != bearerKey {
		err = fmt.Errorf("Authorization type is different from %s", bearerKey)
		return res, err
	}
	token := authData[1]
	token = strings.TrimSpace(token)

	if len(token) == 0 {
		return res, errors.New("Lenght of authorization token must be greater zero")
	}
	res = token
	return res, err
}

func HaveBearerToken(authHeader string) bool {
	const bearerKey = "Bearer"
	const numWords = 2

	authData := strings.SplitN(authHeader, " ", numWords)
	if len(authData) < numWords {
		return false
	}

	authKey := strings.TrimSpace(authData[0])
	if authKey != bearerKey {
		return false
	}
	token := authData[1]
	token = strings.TrimSpace(token)

	if len(token) == 0 {
		return false
	}
	return true
}
