package jwt_adapter

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/dgrijalva/jwt-go"
)

const (
	DefaultAccessSecret = "awesomeAC"
	DefaultHeaderKey    = "Authorization"
	RoleKey             = "role"
)

var (
	accessSecret = DefaultAccessSecret
)

type JwtAdapter struct {
	jwt.StandardClaims
	Id string `json:"id"`
}

func init() {
	aS := os.Getenv("JWT_SECRET")

	if len(aS) != 0 {
		accessSecret = aS
	}
}

func Get(ctx context.Context) *JwtAdapter {
	if adapter, ok := ctx.Value(DefaultHeaderKey).(*JwtAdapter); ok {
		return adapter
	}

	return nil
}

func (receiver *JwtAdapter) SetUserID(ID string) {
	receiver.Id = ID
}

func (receiver *JwtAdapter) GetUserID() string {
	return receiver.Id
}

func (receiver *JwtAdapter) Validate() error {
	if err := receiver.Valid(); err != nil {
		return err
	}

	if !receiver.VerifyIssuer("pena-auth-service", true) {
		return fmt.Errorf("invalid issuer")
	}

	if !receiver.VerifyAudience("pena", true) {
		return fmt.Errorf("invalid audience")
	}

	return nil
}

func Decode(tokenString string) (*JwtAdapter, error) {
	token, err := jwt.ParseWithClaims(tokenString, &JwtAdapter{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}

		return jwt.ParseRSAPublicKeyFromPEM([]byte(accessSecret))
	})

	if err != nil {
		fmt.Println("parserr", err)
		return nil, err
	}

	claims, ok := token.Claims.(*JwtAdapter)
	if !ok && !token.Valid {
		return nil, fmt.Errorf("ErrorNoValidClaims")
	}

	if err := claims.Validate(); err != nil {
		fmt.Println("validerr", err)
		return nil, err
	}

	return claims, nil
}

func GetRole(ctx context.Context) string {
	role := ctx.Value(RoleKey)
	if role == nil {
		return ""
	}
	return role.(string)
}

func Timestamp() int64 {
	return time.Now().UnixNano() / int64(time.Millisecond)
}
