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

package jws

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

	"github.com/lestrrat-go/blackmagic"
	"github.com/lestrrat-go/jwx/v3/cert"
	"github.com/lestrrat-go/jwx/v3/internal/base64"
	"github.com/lestrrat-go/jwx/v3/internal/json"
	"github.com/lestrrat-go/jwx/v3/internal/pool"
	"github.com/lestrrat-go/jwx/v3/internal/tokens"
	"github.com/lestrrat-go/jwx/v3/jwa"
	"github.com/lestrrat-go/jwx/v3/jwk"
)

const (
	AlgorithmKey              = "alg"
	ContentTypeKey            = "cty"
	CriticalKey               = "crit"
	JWKKey                    = "jwk"
	JWKSetURLKey              = "jku"
	KeyIDKey                  = "kid"
	TypeKey                   = "typ"
	X509CertChainKey          = "x5c"
	X509CertThumbprintKey     = "x5t"
	X509CertThumbprintS256Key = "x5t#S256"
	X509URLKey                = "x5u"
)

// Headers describe a standard JWS Header set. It is part of the JWS message
// and is used to represet both Public or Protected headers, which in turn
// can be found in each Signature object. If you are not sure how this works,
// it is strongly recommended that you read RFC7515, especially the section
// that describes the full JSON serialization format of JWS messages.
//
// In most cases, you likely want to use the protected headers, as this is part of the signed content.
type Headers interface {
	Algorithm() (jwa.SignatureAlgorithm, bool)
	ContentType() (string, bool)
	Critical() ([]string, bool)
	JWK() (jwk.Key, bool)
	JWKSetURL() (string, bool)
	KeyID() (string, bool)
	Type() (string, bool)
	X509CertChain() (*cert.Chain, bool)
	X509CertThumbprint() (string, bool)
	X509CertThumbprintS256() (string, bool)
	X509URL() (string, bool)
	Copy(Headers) error
	Merge(Headers) (Headers, error)
	Clone() (Headers, error)
	// Get is used to extract the value of any field, including non-standard fields, out of the header.
	//
	// The first argument is the name of the field. The second argument is a pointer
	// to a variable that will receive the value of the field. The method returns
	// an error if the field 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.
	Get(string, any) error
	Set(string, any) error
	Remove(string) error
	// Has returns true if the specified header 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
	Keys() []string
}

// stdHeaderNames is a list of all standard header names defined in the JWS specification.
var stdHeaderNames = []string{AlgorithmKey, ContentTypeKey, CriticalKey, JWKKey, JWKSetURLKey, KeyIDKey, TypeKey, X509CertChainKey, X509CertThumbprintKey, X509CertThumbprintS256Key, X509URLKey}

type stdHeaders struct {
	algorithm              *jwa.SignatureAlgorithm // https://tools.ietf.org/html/rfc7515#section-4.1.1
	contentType            *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.10
	critical               []string                // https://tools.ietf.org/html/rfc7515#section-4.1.11
	jwk                    jwk.Key                 // https://tools.ietf.org/html/rfc7515#section-4.1.3
	jwkSetURL              *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.2
	keyID                  *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.4
	typ                    *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.9
	x509CertChain          *cert.Chain             // https://tools.ietf.org/html/rfc7515#section-4.1.6
	x509CertThumbprint     *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.7
	x509CertThumbprintS256 *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.8
	x509URL                *string                 // https://tools.ietf.org/html/rfc7515#section-4.1.5
	privateParams          map[string]any
	mu                     *sync.RWMutex
	dc                     DecodeCtx
	raw                    []byte // stores the raw version of the header so it can be used later
}

func NewHeaders() Headers {
	return &stdHeaders{
		mu: &sync.RWMutex{},
	}
}

func (h *stdHeaders) Algorithm() (jwa.SignatureAlgorithm, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.algorithm == nil {
		return jwa.EmptySignatureAlgorithm(), false
	}
	return *(h.algorithm), true
}

func (h *stdHeaders) ContentType() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.contentType == nil {
		return "", false
	}
	return *(h.contentType), true
}

func (h *stdHeaders) Critical() ([]string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.critical, true
}

func (h *stdHeaders) JWK() (jwk.Key, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.jwk, true
}

func (h *stdHeaders) JWKSetURL() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.jwkSetURL == nil {
		return "", false
	}
	return *(h.jwkSetURL), true
}

func (h *stdHeaders) KeyID() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.keyID == nil {
		return "", false
	}
	return *(h.keyID), true
}

func (h *stdHeaders) Type() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.typ == nil {
		return "", false
	}
	return *(h.typ), true
}

func (h *stdHeaders) X509CertChain() (*cert.Chain, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.x509CertChain, true
}

func (h *stdHeaders) X509CertThumbprint() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509CertThumbprint == nil {
		return "", false
	}
	return *(h.x509CertThumbprint), true
}

func (h *stdHeaders) X509CertThumbprintS256() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509CertThumbprintS256 == nil {
		return "", false
	}
	return *(h.x509CertThumbprintS256), true
}

func (h *stdHeaders) X509URL() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509URL == nil {
		return "", false
	}
	return *(h.x509URL), true
}

func (h *stdHeaders) clear() {
	h.algorithm = nil
	h.contentType = nil
	h.critical = nil
	h.jwk = nil
	h.jwkSetURL = nil
	h.keyID = nil
	h.typ = nil
	h.x509CertChain = nil
	h.x509CertThumbprint = nil
	h.x509CertThumbprintS256 = nil
	h.x509URL = nil
	h.privateParams = nil
	h.raw = nil
}

func (h *stdHeaders) DecodeCtx() DecodeCtx {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.dc
}

func (h *stdHeaders) SetDecodeCtx(dc DecodeCtx) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.dc = dc
}

func (h *stdHeaders) rawBuffer() []byte {
	return h.raw
}

func (h *stdHeaders) PrivateParams() map[string]any {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return h.privateParams
}

func (h *stdHeaders) Has(name string) bool {
	h.mu.RLock()
	defer h.mu.RUnlock()
	switch name {
	case AlgorithmKey:
		return h.algorithm != nil
	case ContentTypeKey:
		return h.contentType != nil
	case CriticalKey:
		return h.critical != nil
	case JWKKey:
		return h.jwk != nil
	case JWKSetURLKey:
		return h.jwkSetURL != nil
	case KeyIDKey:
		return h.keyID != nil
	case TypeKey:
		return h.typ != nil
	case X509CertChainKey:
		return h.x509CertChain != nil
	case X509CertThumbprintKey:
		return h.x509CertThumbprint != nil
	case X509CertThumbprintS256Key:
		return h.x509CertThumbprintS256 != nil
	case X509URLKey:
		return h.x509URL != nil
	default:
		_, ok := h.privateParams[name]
		return ok
	}
}

func (h *stdHeaders) Get(name string, dst any) error {
	h.mu.RLock()
	defer h.mu.RUnlock()
	switch name {
	case AlgorithmKey:
		if h.algorithm == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.algorithm)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case ContentTypeKey:
		if h.contentType == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.contentType)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case CriticalKey:
		if h.critical == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst,
			h.critical); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case JWKKey:
		if h.jwk == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst,
			h.jwk); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case JWKSetURLKey:
		if h.jwkSetURL == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.jwkSetURL)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case KeyIDKey:
		if h.keyID == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.keyID)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case TypeKey:
		if h.typ == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.typ)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509CertChainKey:
		if h.x509CertChain == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst,
			h.x509CertChain); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509CertThumbprintKey:
		if h.x509CertThumbprint == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509CertThumbprint)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509CertThumbprintS256Key:
		if h.x509CertThumbprintS256 == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509CertThumbprintS256)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509URLKey:
		if h.x509URL == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509URL)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	default:
		v, ok := h.privateParams[name]
		if !ok {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, v); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	}
	return nil
}

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

func (h *stdHeaders) setNoLock(name string, value any) error {
	switch name {
	case AlgorithmKey:
		alg, err := jwa.KeyAlgorithmFrom(value)
		if err != nil {
			return fmt.Errorf("invalid value for %s key: %w", AlgorithmKey, err)
		}
		if salg, ok := alg.(jwa.SignatureAlgorithm); ok {
			h.algorithm = &salg
			return nil
		}
		return fmt.Errorf("expecte jwa.SignatureAlgorithm, received %T", alg)
	case ContentTypeKey:
		if v, ok := value.(string); ok {
			h.contentType = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, ContentTypeKey, value)
	case CriticalKey:
		if v, ok := value.([]string); ok {
			h.critical = v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, CriticalKey, value)
	case JWKKey:
		if v, ok := value.(jwk.Key); ok {
			h.jwk = v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, JWKKey, value)
	case JWKSetURLKey:
		if v, ok := value.(string); ok {
			h.jwkSetURL = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, JWKSetURLKey, value)
	case KeyIDKey:
		if v, ok := value.(string); ok {
			h.keyID = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, KeyIDKey, value)
	case TypeKey:
		if v, ok := value.(string); ok {
			h.typ = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, TypeKey, value)
	case X509CertChainKey:
		if v, ok := value.(*cert.Chain); ok {
			h.x509CertChain = v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertChainKey, value)
	case X509CertThumbprintKey:
		if v, ok := value.(string); ok {
			h.x509CertThumbprint = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintKey, value)
	case X509CertThumbprintS256Key:
		if v, ok := value.(string); ok {
			h.x509CertThumbprintS256 = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintS256Key, value)
	case X509URLKey:
		if v, ok := value.(string); ok {
			h.x509URL = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509URLKey, value)
	default:
		if h.privateParams == nil {
			h.privateParams = map[string]any{}
		}
		h.privateParams[name] = value
	}
	return nil
}

func (h *stdHeaders) Remove(key string) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	switch key {
	case AlgorithmKey:
		h.algorithm = nil
	case ContentTypeKey:
		h.contentType = nil
	case CriticalKey:
		h.critical = nil
	case JWKKey:
		h.jwk = nil
	case JWKSetURLKey:
		h.jwkSetURL = nil
	case KeyIDKey:
		h.keyID = nil
	case TypeKey:
		h.typ = nil
	case X509CertChainKey:
		h.x509CertChain = nil
	case X509CertThumbprintKey:
		h.x509CertThumbprint = nil
	case X509CertThumbprintS256Key:
		h.x509CertThumbprintS256 = nil
	case X509URLKey:
		h.x509URL = nil
	default:
		delete(h.privateParams, key)
	}
	return nil
}

func (h *stdHeaders) UnmarshalJSON(buf []byte) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.clear()
	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 AlgorithmKey:
				var decoded jwa.SignatureAlgorithm
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, AlgorithmKey, err)
				}
				h.algorithm = &decoded
			case ContentTypeKey:
				if err := json.AssignNextStringToken(&h.contentType, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, ContentTypeKey, err)
				}
			case CriticalKey:
				var decoded []string
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, CriticalKey, err)
				}
				h.critical = decoded
			case JWKKey:
				var buf json.RawMessage
				if err := dec.Decode(&buf); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, JWKKey, err)
				}
				key, err := jwk.ParseKey(buf)
				if err != nil {
					return fmt.Errorf(`failed to parse JWK for key %s: %w`, JWKKey, err)
				}
				h.jwk = key
			case JWKSetURLKey:
				if err := json.AssignNextStringToken(&h.jwkSetURL, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, JWKSetURLKey, err)
				}
			case KeyIDKey:
				if err := json.AssignNextStringToken(&h.keyID, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyIDKey, err)
				}
			case TypeKey:
				if err := json.AssignNextStringToken(&h.typ, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, TypeKey, err)
				}
			case X509CertChainKey:
				var decoded cert.Chain
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertChainKey, err)
				}
				h.x509CertChain = &decoded
			case X509CertThumbprintKey:
				if err := json.AssignNextStringToken(&h.x509CertThumbprint, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintKey, err)
				}
			case X509CertThumbprintS256Key:
				if err := json.AssignNextStringToken(&h.x509CertThumbprintS256, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintS256Key, err)
				}
			case X509URLKey:
				if err := json.AssignNextStringToken(&h.x509URL, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509URLKey, err)
				}
			default:
				decoded, err := registry.Decode(dec, tok)
				if err != nil {
					return err
				}
				h.setNoLock(tok, decoded)
			}
		default:
			return fmt.Errorf(`invalid token %T`, tok)
		}
	}
	h.raw = buf
	return nil
}

func (h *stdHeaders) Keys() []string {
	h.mu.RLock()
	defer h.mu.RUnlock()
	keys := make([]string, 0, 11+len(h.privateParams))
	if h.algorithm != nil {
		keys = append(keys, AlgorithmKey)
	}
	if h.contentType != nil {
		keys = append(keys, ContentTypeKey)
	}
	if h.critical != nil {
		keys = append(keys, CriticalKey)
	}
	if h.jwk != nil {
		keys = append(keys, JWKKey)
	}
	if h.jwkSetURL != nil {
		keys = append(keys, JWKSetURLKey)
	}
	if h.keyID != nil {
		keys = append(keys, KeyIDKey)
	}
	if h.typ != nil {
		keys = append(keys, TypeKey)
	}
	if h.x509CertChain != nil {
		keys = append(keys, X509CertChainKey)
	}
	if h.x509CertThumbprint != nil {
		keys = append(keys, X509CertThumbprintKey)
	}
	if h.x509CertThumbprintS256 != nil {
		keys = append(keys, X509CertThumbprintS256Key)
	}
	if h.x509URL != nil {
		keys = append(keys, X509URLKey)
	}
	for k := range h.privateParams {
		keys = append(keys, k)
	}
	return keys
}

func (h stdHeaders) MarshalJSON() ([]byte, error) {
	h.mu.RLock()
	data := make(map[string]any)
	keys := make([]string, 0, 11+len(h.privateParams))
	if h.algorithm != nil {
		data[AlgorithmKey] = *(h.algorithm)
		keys = append(keys, AlgorithmKey)
	}
	if h.contentType != nil {
		data[ContentTypeKey] = *(h.contentType)
		keys = append(keys, ContentTypeKey)
	}
	if h.critical != nil {
		data[CriticalKey] = h.critical
		keys = append(keys, CriticalKey)
	}
	if h.jwk != nil {
		data[JWKKey] = h.jwk
		keys = append(keys, JWKKey)
	}
	if h.jwkSetURL != nil {
		data[JWKSetURLKey] = *(h.jwkSetURL)
		keys = append(keys, JWKSetURLKey)
	}
	if h.keyID != nil {
		data[KeyIDKey] = *(h.keyID)
		keys = append(keys, KeyIDKey)
	}
	if h.typ != nil {
		data[TypeKey] = *(h.typ)
		keys = append(keys, TypeKey)
	}
	if h.x509CertChain != nil {
		data[X509CertChainKey] = h.x509CertChain
		keys = append(keys, X509CertChainKey)
	}
	if h.x509CertThumbprint != nil {
		data[X509CertThumbprintKey] = *(h.x509CertThumbprint)
		keys = append(keys, X509CertThumbprintKey)
	}
	if h.x509CertThumbprintS256 != nil {
		data[X509CertThumbprintS256Key] = *(h.x509CertThumbprintS256)
		keys = append(keys, X509CertThumbprintS256Key)
	}
	if h.x509URL != nil {
		data[X509URLKey] = *(h.x509URL)
		keys = append(keys, X509URLKey)
	}
	for k, v := range h.privateParams {
		data[k] = v
		keys = append(keys, k)
	}
	h.mu.RUnlock()
	sort.Strings(keys)
	buf := pool.BytesBuffer().Get()
	defer pool.BytesBuffer().Put(buf)
	enc := json.NewEncoder(buf)
	buf.WriteByte(tokens.OpenCurlyBracket)
	for i, k := range keys {
		if i > 0 {
			buf.WriteRune(tokens.Comma)
		}
		buf.WriteRune(tokens.DoubleQuote)
		buf.WriteString(k)
		buf.WriteString(`":`)
		switch v := data[k].(type) {
		case []byte:
			buf.WriteRune(tokens.DoubleQuote)
			buf.WriteString(base64.EncodeToString(v))
			buf.WriteRune(tokens.DoubleQuote)
		default:
			if err := enc.Encode(v); err != nil {
				return nil, fmt.Errorf(`failed to encode value for field %s: %w`, k, err)
			}
			buf.Truncate(buf.Len() - 1)
		}
	}
	buf.WriteByte(tokens.CloseCurlyBracket)
	ret := make([]byte, buf.Len())
	copy(ret, buf.Bytes())
	return ret, nil
}
