// Code generated by tools/cmd/genjwt/main.go. DO NOT EDIT.

package jwt

import (
	"bytes"
	"fmt"
	"sort"
	"sync"
	"time"

	"github.com/lestrrat-go/blackmagic"
	"github.com/lestrrat-go/jwx/v3/internal/json"
	"github.com/lestrrat-go/jwx/v3/internal/pool"
	"github.com/lestrrat-go/jwx/v3/internal/tokens"
	jwterrs "github.com/lestrrat-go/jwx/v3/jwt/internal/errors"
	"github.com/lestrrat-go/jwx/v3/jwt/internal/types"
)

const (
	AudienceKey   = "aud"
	ExpirationKey = "exp"
	IssuedAtKey   = "iat"
	IssuerKey     = "iss"
	JwtIDKey      = "jti"
	NotBeforeKey  = "nbf"
	SubjectKey    = "sub"
)

// stdClaimNames is a list of all standard claim names defined in the JWT specification.
var stdClaimNames = []string{AudienceKey, ExpirationKey, IssuedAtKey, IssuerKey, JwtIDKey, NotBeforeKey, SubjectKey}

// Token represents a generic JWT token.
// which are type-aware (to an extent). Other claims may be accessed via the `Get`/`Set`
// methods but their types are not taken into consideration at all. If you have non-standard
// claims that you must frequently access, consider creating accessors functions
// like the following
//
// func SetFoo(tok jwt.Token) error
// func GetFoo(tok jwt.Token) (*Customtyp, error)
//
// Embedding jwt.Token into another struct is not recommended, because
// jwt.Token needs to handle private claims, and this really does not
// work well when it is embedded in other structure
type Token interface {
	// Audience returns the value for "aud" field of the token
	Audience() ([]string, bool)

	// Expiration returns the value for "exp" field of the token
	Expiration() (time.Time, bool)

	// IssuedAt returns the value for "iat" field of the token
	IssuedAt() (time.Time, bool)

	// Issuer returns the value for "iss" field of the token
	Issuer() (string, bool)

	// JwtID returns the value for "jti" field of the token
	JwtID() (string, bool)

	// NotBefore returns the value for "nbf" field of the token
	NotBefore() (time.Time, bool)

	// Subject returns the value for "sub" field of the token
	Subject() (string, bool)

	// Get is used to extract the value of any claim, including non-standard claims, out of the token.
	//
	// The first argument is the name of the claim. The second argument is a pointer
	// to a variable that will receive the value of the claim. The method returns
	// an error if the claim does not exist, or if the value cannot be assigned to
	// the destination variable.  Note that a field is considered to "exist" even if
	// the value is empty-ish (e.g. 0, false, ""), as long as it is explicitly set.
	//
	// For standard claims, you can use the corresponding getter method, such as
	// `Issuer()`, `Subject()`, `Audience()`, `IssuedAt()`, `NotBefore()`, `ExpiresAt()`
	//
	// Note that fields of JWS/JWE are NOT accessible through this method. You need
	// to use `jws.Parse` and `jwe.Parse` to obtain the JWS/JWE message (and NOT
	// the payload, which presumably is the JWT), and then use their `Get` methods in their respective packages
	Get(string, any) error

	// Set assigns a value to the corresponding field in the token. Some
	// pre-defined fields such as `nbf`, `iat`, `iss` need their values to
	// be of a specific type. See the other getter methods in this interface
	// for the types of each of these fields
	Set(string, any) error

	// Has returns true if the specified claim has a value, even if
	// the value is empty-ish (e.g. 0, false, "")  as long as it has been
	// explicitly set.
	Has(string) bool
	Remove(string) error

	// Options returns the per-token options associated with this token.
	// The options set value will be copied when the token is cloned via `Clone()`
	// but it will not survive when the token goes through marshaling/unmarshaling
	// such as `json.Marshal` and `json.Unmarshal`
	Options() *TokenOptionSet
	Clone() (Token, error)
	Keys() []string
}
type stdToken struct {
	mu            *sync.RWMutex
	dc            DecodeCtx          // per-object context for decoding
	options       TokenOptionSet     // per-object option
	audience      types.StringList   // https://tools.ietf.org/html/rfc7519#section-4.1.3
	expiration    *types.NumericDate // https://tools.ietf.org/html/rfc7519#section-4.1.4
	issuedAt      *types.NumericDate // https://tools.ietf.org/html/rfc7519#section-4.1.6
	issuer        *string            // https://tools.ietf.org/html/rfc7519#section-4.1.1
	jwtID         *string            // https://tools.ietf.org/html/rfc7519#section-4.1.7
	notBefore     *types.NumericDate // https://tools.ietf.org/html/rfc7519#section-4.1.5
	subject       *string            // https://tools.ietf.org/html/rfc7519#section-4.1.2
	privateClaims map[string]any
}

// New creates a standard token, with minimal knowledge of
// possible claims. Standard claims include"aud", "exp", "iat", "iss", "jti", "nbf" and "sub".
// Convenience accessors are provided for these standard claims
func New() Token {
	return &stdToken{
		mu:            &sync.RWMutex{},
		privateClaims: make(map[string]any),
		options:       DefaultOptionSet(),
	}
}

func (t *stdToken) Options() *TokenOptionSet {
	return &t.options
}

func (t *stdToken) Has(name string) bool {
	t.mu.RLock()
	defer t.mu.RUnlock()
	switch name {
	case AudienceKey:
		return t.audience != nil
	case ExpirationKey:
		return t.expiration != nil
	case IssuedAtKey:
		return t.issuedAt != nil
	case IssuerKey:
		return t.issuer != nil
	case JwtIDKey:
		return t.jwtID != nil
	case NotBeforeKey:
		return t.notBefore != nil
	case SubjectKey:
		return t.subject != nil
	default:
		_, ok := t.privateClaims[name]
		return ok
	}
}

func (t *stdToken) Get(name string, dst any) error {
	t.mu.RLock()
	defer t.mu.RUnlock()
	switch name {
	case AudienceKey:
		if t.audience == nil {
			return jwterrs.ClaimNotFoundError{Name: name}
		}
		if err := blackmagic.AssignIfCompatible(dst, t.audience.Get()); err != nil {
			return jwterrs.ClaimAssignmentFailedError{Err: err}
		}
		return nil
	case ExpirationKey:
		if t.expiration == nil {
			return jwterrs.ClaimNotFoundError{Name: name}
		}
		if err := blackmagic.AssignIfCompatible(dst, t.expiration.Get()); err != nil {
			return jwterrs.ClaimAssignmentFailedError{Err: err}
		}
		return nil
	case IssuedAtKey:
		if t.issuedAt == nil {
			return jwterrs.ClaimNotFoundError{Name: name}
		}
		if err := blackmagic.AssignIfCompatible(dst, t.issuedAt.Get()); err != nil {
			return jwterrs.ClaimAssignmentFailedError{Err: err}
		}
		return nil
	case IssuerKey:
		if t.issuer == nil {
			return jwterrs.ClaimNotFoundError{Name: name}
		}
		if err := blackmagic.AssignIfCompatible(dst, *(t.issuer)); err != nil {
			return jwterrs.ClaimAssignmentFailedError{Err: err}
		}
		return nil
	case JwtIDKey:
		if t.jwtID == nil {
			return jwterrs.ClaimNotFoundError{Name: name}
		}
		if err := blackmagic.AssignIfCompatible(dst, *(t.jwtID)); err != nil {
			return jwterrs.ClaimAssignmentFailedError{Err: err}
		}
		return nil
	case NotBeforeKey:
		if t.notBefore == nil {
			return jwterrs.ClaimNotFoundError{Name: name}
		}
		if err := blackmagic.AssignIfCompatible(dst, t.notBefore.Get()); err != nil {
			return jwterrs.ClaimAssignmentFailedError{Err: err}
		}
		return nil
	case SubjectKey:
		if t.subject == nil {
			return jwterrs.ClaimNotFoundError{Name: name}
		}
		if err := blackmagic.AssignIfCompatible(dst, *(t.subject)); err != nil {
			return jwterrs.ClaimAssignmentFailedError{Err: err}
		}
		return nil
	default:
		v, ok := t.privateClaims[name]
		if !ok {
			return jwterrs.ClaimNotFoundError{Name: name}
		}
		if err := blackmagic.AssignIfCompatible(dst, v); err != nil {
			return jwterrs.ClaimAssignmentFailedError{Err: err}
		}
		return nil
	}
}

func (t *stdToken) Remove(key string) error {
	t.mu.Lock()
	defer t.mu.Unlock()
	switch key {
	case AudienceKey:
		t.audience = nil
	case ExpirationKey:
		t.expiration = nil
	case IssuedAtKey:
		t.issuedAt = nil
	case IssuerKey:
		t.issuer = nil
	case JwtIDKey:
		t.jwtID = nil
	case NotBeforeKey:
		t.notBefore = nil
	case SubjectKey:
		t.subject = nil
	default:
		delete(t.privateClaims, key)
	}
	return nil
}

func (t *stdToken) Set(name string, value any) error {
	t.mu.Lock()
	defer t.mu.Unlock()
	return t.setNoLock(name, value)
}

func (t *stdToken) DecodeCtx() DecodeCtx {
	t.mu.RLock()
	defer t.mu.RUnlock()
	return t.dc
}

func (t *stdToken) SetDecodeCtx(v DecodeCtx) {
	t.mu.Lock()
	defer t.mu.Unlock()
	t.dc = v
}

func (t *stdToken) setNoLock(name string, value any) error {
	switch name {
	case AudienceKey:
		var acceptor types.StringList
		if err := acceptor.Accept(value); err != nil {
			return fmt.Errorf(`invalid value for %s key: %w`, AudienceKey, err)
		}
		t.audience = acceptor
		return nil
	case ExpirationKey:
		var acceptor types.NumericDate
		if err := acceptor.Accept(value); err != nil {
			return fmt.Errorf(`invalid value for %s key: %w`, ExpirationKey, err)
		}
		t.expiration = &acceptor
		return nil
	case IssuedAtKey:
		var acceptor types.NumericDate
		if err := acceptor.Accept(value); err != nil {
			return fmt.Errorf(`invalid value for %s key: %w`, IssuedAtKey, err)
		}
		t.issuedAt = &acceptor
		return nil
	case IssuerKey:
		if v, ok := value.(string); ok {
			t.issuer = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, IssuerKey, value)
	case JwtIDKey:
		if v, ok := value.(string); ok {
			t.jwtID = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, JwtIDKey, value)
	case NotBeforeKey:
		var acceptor types.NumericDate
		if err := acceptor.Accept(value); err != nil {
			return fmt.Errorf(`invalid value for %s key: %w`, NotBeforeKey, err)
		}
		t.notBefore = &acceptor
		return nil
	case SubjectKey:
		if v, ok := value.(string); ok {
			t.subject = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, SubjectKey, value)
	default:
		if t.privateClaims == nil {
			t.privateClaims = map[string]any{}
		}
		t.privateClaims[name] = value
	}
	return nil
}

func (t *stdToken) Audience() ([]string, bool) {
	t.mu.RLock()
	defer t.mu.RUnlock()
	if t.audience != nil {
		return t.audience.Get(), true
	}
	return nil, false
}

func (t *stdToken) Expiration() (time.Time, bool) {
	t.mu.RLock()
	defer t.mu.RUnlock()
	if t.expiration != nil {
		return t.expiration.Get(), true
	}
	return time.Time{}, false
}

func (t *stdToken) IssuedAt() (time.Time, bool) {
	t.mu.RLock()
	defer t.mu.RUnlock()
	if t.issuedAt != nil {
		return t.issuedAt.Get(), true
	}
	return time.Time{}, false
}

func (t *stdToken) Issuer() (string, bool) {
	t.mu.RLock()
	defer t.mu.RUnlock()
	if t.issuer != nil {
		return *(t.issuer), true
	}
	return "", false
}

func (t *stdToken) JwtID() (string, bool) {
	t.mu.RLock()
	defer t.mu.RUnlock()
	if t.jwtID != nil {
		return *(t.jwtID), true
	}
	return "", false
}

func (t *stdToken) NotBefore() (time.Time, bool) {
	t.mu.RLock()
	defer t.mu.RUnlock()
	if t.notBefore != nil {
		return t.notBefore.Get(), true
	}
	return time.Time{}, false
}

func (t *stdToken) Subject() (string, bool) {
	t.mu.RLock()
	defer t.mu.RUnlock()
	if t.subject != nil {
		return *(t.subject), true
	}
	return "", false
}

func (t *stdToken) PrivateClaims() map[string]any {
	t.mu.RLock()
	defer t.mu.RUnlock()
	return t.privateClaims
}

func (t *stdToken) UnmarshalJSON(buf []byte) error {
	t.mu.Lock()
	defer t.mu.Unlock()
	t.audience = nil
	t.expiration = nil
	t.issuedAt = nil
	t.issuer = nil
	t.jwtID = nil
	t.notBefore = nil
	t.subject = nil
	dec := json.NewDecoder(bytes.NewReader(buf))
LOOP:
	for {
		tok, err := dec.Token()
		if err != nil {
			return fmt.Errorf(`error reading token: %w`, err)
		}
		switch tok := tok.(type) {
		case json.Delim:
			// Assuming we're doing everything correctly, we should ONLY
			// get either tokens.OpenCurlyBracket or tokens.CloseCurlyBracket here.
			if tok == tokens.CloseCurlyBracket { // End of object
				break LOOP
			} else if tok != tokens.OpenCurlyBracket {
				return fmt.Errorf(`expected '%c', but got '%c'`, tokens.OpenCurlyBracket, tok)
			}
		case string: // Objects can only have string keys
			switch tok {
			case AudienceKey:
				var decoded types.StringList
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, AudienceKey, err)
				}
				t.audience = decoded
			case ExpirationKey:
				var decoded types.NumericDate
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, ExpirationKey, err)
				}
				t.expiration = &decoded
			case IssuedAtKey:
				var decoded types.NumericDate
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, IssuedAtKey, err)
				}
				t.issuedAt = &decoded
			case IssuerKey:
				if err := json.AssignNextStringToken(&t.issuer, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, IssuerKey, err)
				}
			case JwtIDKey:
				if err := json.AssignNextStringToken(&t.jwtID, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, JwtIDKey, err)
				}
			case NotBeforeKey:
				var decoded types.NumericDate
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, NotBeforeKey, err)
				}
				t.notBefore = &decoded
			case SubjectKey:
				if err := json.AssignNextStringToken(&t.subject, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, SubjectKey, err)
				}
			default:
				if dc := t.dc; dc != nil {
					if localReg := dc.Registry(); localReg != nil {
						decoded, err := localReg.Decode(dec, tok)
						if err == nil {
							t.setNoLock(tok, decoded)
							continue
						}
					}
				}
				decoded, err := registry.Decode(dec, tok)
				if err == nil {
					t.setNoLock(tok, decoded)
					continue
				}
				return fmt.Errorf(`could not decode field %s: %w`, tok, err)
			}
		default:
			return fmt.Errorf(`invalid token %T`, tok)
		}
	}
	return nil
}

func (t *stdToken) Keys() []string {
	t.mu.RLock()
	defer t.mu.RUnlock()
	keys := make([]string, 0, 7+len(t.privateClaims))
	if t.audience != nil {
		keys = append(keys, AudienceKey)
	}
	if t.expiration != nil {
		keys = append(keys, ExpirationKey)
	}
	if t.issuedAt != nil {
		keys = append(keys, IssuedAtKey)
	}
	if t.issuer != nil {
		keys = append(keys, IssuerKey)
	}
	if t.jwtID != nil {
		keys = append(keys, JwtIDKey)
	}
	if t.notBefore != nil {
		keys = append(keys, NotBeforeKey)
	}
	if t.subject != nil {
		keys = append(keys, SubjectKey)
	}
	for k := range t.privateClaims {
		keys = append(keys, k)
	}
	return keys
}

type claimPair struct {
	Name  string
	Value any
}

var claimPairPool = sync.Pool{
	New: func() any {
		return make([]claimPair, 0, 7)
	},
}

func getClaimPairList() []claimPair {
	return claimPairPool.Get().([]claimPair)
}

func putClaimPairList(list []claimPair) {
	list = list[:0]
	claimPairPool.Put(list)
}

// makePairs creates a list of claimPair objects that are sorted by
// their key names. The key names are always their JSON names, and
// the values are already JSON encoded.
// Because makePairs needs to allocate a slice, it _slows_ down
// marshaling of the token to JSON. The upside is that it allows us to
// marshal the token keys in a deterministic order.
// Do we really need it...? Well, technically we don't, but it's so
// much nicer to have this to make the example tests actually work
// deterministically. Also if for whatever reason this becomes a
// performance issue, we can always/ add a flag to use a more _optimized_ code path.
//
// The caller is responsible to call putClaimPairList() to return the
// allocated slice back to the pool.

func (t *stdToken) makePairs() ([]claimPair, error) {
	pairs := getClaimPairList()
	if t.audience != nil {
		buf, err := json.MarshalAudience(t.audience, t.options.IsEnabled(FlattenAudience))
		if err != nil {
			return nil, fmt.Errorf(`failed to encode "aud": %w`, err)
		}
		pairs = append(pairs, claimPair{Name: AudienceKey, Value: buf})
	}
	if t.expiration != nil {
		buf, err := json.Marshal(t.expiration.Unix())
		if err != nil {
			return nil, fmt.Errorf(`failed to encode "exp": %w`, err)
		}
		pairs = append(pairs, claimPair{Name: ExpirationKey, Value: buf})
	}
	if t.issuedAt != nil {
		buf, err := json.Marshal(t.issuedAt.Unix())
		if err != nil {
			return nil, fmt.Errorf(`failed to encode "iat": %w`, err)
		}
		pairs = append(pairs, claimPair{Name: IssuedAtKey, Value: buf})
	}
	if t.issuer != nil {
		buf, err := json.Marshal(*(t.issuer))
		if err != nil {
			return nil, fmt.Errorf(`failed to encode field "iss": %w`, err)
		}
		pairs = append(pairs, claimPair{Name: IssuerKey, Value: buf})
	}
	if t.jwtID != nil {
		buf, err := json.Marshal(*(t.jwtID))
		if err != nil {
			return nil, fmt.Errorf(`failed to encode field "jti": %w`, err)
		}
		pairs = append(pairs, claimPair{Name: JwtIDKey, Value: buf})
	}
	if t.notBefore != nil {
		buf, err := json.Marshal(t.notBefore.Unix())
		if err != nil {
			return nil, fmt.Errorf(`failed to encode "nbf": %w`, err)
		}
		pairs = append(pairs, claimPair{Name: NotBeforeKey, Value: buf})
	}
	if t.subject != nil {
		buf, err := json.Marshal(*(t.subject))
		if err != nil {
			return nil, fmt.Errorf(`failed to encode field "sub": %w`, err)
		}
		pairs = append(pairs, claimPair{Name: SubjectKey, Value: buf})
	}
	for k, v := range t.privateClaims {
		buf, err := json.Marshal(v)
		if err != nil {
			return nil, fmt.Errorf(`failed to encode field %q: %w`, k, err)
		}
		pairs = append(pairs, claimPair{Name: k, Value: buf})
	}

	sort.Slice(pairs, func(i, j int) bool {
		return pairs[i].Name < pairs[j].Name
	})

	return pairs, nil
}

func (t stdToken) MarshalJSON() ([]byte, error) {
	buf := pool.BytesBuffer().Get()
	defer pool.BytesBuffer().Put(buf)
	pairs, err := t.makePairs()
	if err != nil {
		return nil, fmt.Errorf(`failed to make pairs: %w`, err)
	}
	buf.WriteByte(tokens.OpenCurlyBracket)

	for i, pair := range pairs {
		if i > 0 {
			buf.WriteByte(tokens.Comma)
		}
		fmt.Fprintf(buf, "%q: %s", pair.Name, pair.Value)
	}
	buf.WriteByte(tokens.CloseCurlyBracket)
	ret := make([]byte, buf.Len())
	copy(ret, buf.Bytes())
	putClaimPairList(pairs)
	return ret, nil
}
