package token

import (
	"context"
	"strings"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

func GetRequestToken(r *ghttp.Request) (token string) {
	authHeader := r.Header.Get("Authorization")
	if authHeader != "" {
		token = splitTokenFromBearer(authHeader)
	} else {
		authHeader = r.Get("token").String()
		if authHeader == "" {
			return
		}
		token = authHeader
	}
	return
}

func GetTokenFromCtx(ctx context.Context) (token string) {
	authHeader := ghttp.RequestFromCtx(ctx).Header.Get("Authorization")
	if authHeader != "" {
		return splitTokenFromBearer(authHeader)
	}
	authHeader = ghttp.RequestFromCtx(ctx).Header.Get("token")
	if authHeader == "" {
		return
	}
	return authHeader
}

func splitTokenFromBearer(token string) string {
	parts := strings.Split(token, " ")
	if len(parts) == 2 && parts[0] == "Bearer" {
		return parts[1]
	}
	return parts[0]
}

func GetTokenFrom(ctx context.Context) string {
	tokenFrom := g.RequestFromCtx(ctx).Request.Header.Get("tokenFrom")
	return tokenFrom
}

func IsFromLogin(ctx context.Context) bool {
	tokenFrom := GetTokenFrom(ctx)
	return tokenFrom == "login"
}

func IsFromIframe(ctx context.Context) bool {
	tokenFrom := GetTokenFrom(ctx)
	return tokenFrom == "iframe"
}
