package grpctool

import (
	"context"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

const (
	jwtValidFor  = 5 * time.Second
	jwtNotBefore = 5 * time.Second
)

type JWTCredentials struct {
	SigningMethod jwt.SigningMethod
	// Type depends on the SigningMethod:
	// - []byte for HMAC.
	// - *ecdsa.PrivateKey for ECDSA.
	// - *rsa.PrivateKey for RSA.
	// - crypto.Signer for EdDSA.
	SigningKey any
	Audience   string
	Issuer     string
	Insecure   bool
}

func (c *JWTCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	now := time.Now()
	claims := jwt.RegisteredClaims{
		Issuer:    c.Issuer,
		Audience:  jwt.ClaimStrings{c.Audience},
		ExpiresAt: jwt.NewNumericDate(now.Add(jwtValidFor)),
		NotBefore: jwt.NewNumericDate(now.Add(-jwtNotBefore)),
		IssuedAt:  jwt.NewNumericDate(now),
	}
	signedClaims, err := jwt.NewWithClaims(c.SigningMethod, claims).SignedString(c.SigningKey)
	if err != nil {
		return nil, err
	}
	return map[string]string{
		MetadataAuthorization: "Bearer " + signedClaims,
	}, nil
}

func (c *JWTCredentials) RequireTransportSecurity() bool {
	return !c.Insecure
}
