// Code generated by go generate; DO NOT EDIT.
package {{ .Package }}

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"
	"sort"
	"strings"

	"github.com/go-openapi/jsonpointer"
	"github.com/perimeterx/marshmallow"
)
{{ range $type := .Types }}
// {{ $type.Name }}Ref represents either a {{ $type.Name }} or a $ref to a {{ $type.Name }}.
// When serializing and both fields are set, Ref is preferred over Value.
type {{ $type.Name }}Ref struct {
	// Extensions only captures fields starting with 'x-' as no other fields
	// are allowed by the openapi spec.
	Extensions map[string]any
	Origin     *Origin

	Ref   string
	Value *{{ $type.Name }}
	extra []string

	refPath *url.URL
}

var _ jsonpointer.JSONPointable = (*{{ $type.Name }}Ref)(nil)

func (x *{{ $type.Name }}Ref) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil }

// RefString returns the $ref value.
func (x *{{ $type.Name }}Ref) RefString() string { return x.Ref }

// CollectionName returns the JSON string used for a collection of these components.
func (x *{{ $type.Name }}Ref) CollectionName() string { return "{{ $type.CollectionName }}" }

// RefPath returns the path of the $ref relative to the root document.
func (x *{{ $type.Name }}Ref) RefPath() *url.URL { return copyURI(x.refPath) }

func (x *{{ $type.Name }}Ref) setRefPath(u *url.URL) {
	// Once the refPath is set don't override. References can be loaded
	// multiple times not all with access to the correct path info.
	if x.refPath != nil {
		return
	}

	x.refPath = copyURI(u)
}

// MarshalYAML returns the YAML encoding of {{ $type.Name }}Ref.
func (x {{ $type.Name }}Ref) MarshalYAML() (any, error) {
	if ref := x.Ref; ref != "" {
		return &Ref{Ref: ref}, nil
	}
	return x.Value.MarshalYAML()
}

// MarshalJSON returns the JSON encoding of {{ $type.Name }}Ref.
func (x {{ $type.Name }}Ref) MarshalJSON() ([]byte, error) {
	y, err := x.MarshalYAML()
	if err != nil {
		return nil, err
	}
	return json.Marshal(y)
}

// UnmarshalJSON sets {{ $type.Name }}Ref to a copy of data.
func (x *{{ $type.Name }}Ref) UnmarshalJSON(data []byte) error {
	var refOnly Ref
	if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" {
		x.Ref = refOnly.Ref
		x.Origin = refOnly.Origin
		if len(extra) != 0 {
			x.extra = make([]string, 0, len(extra))
			for key := range extra {
				x.extra = append(x.extra, key)
			}
			sort.Strings(x.extra)
			for k := range extra {
				if !strings.HasPrefix(k, "x-") {
					delete(extra, k)
				}
			}
			if len(extra) != 0 {
				x.Extensions = extra
			}
		}
		return nil
	}
	return json.Unmarshal(data, &x.Value)
}

// Validate returns an error if {{ $type.Name }}Ref does not comply with the OpenAPI spec.
func (x *{{ $type.Name }}Ref) Validate(ctx context.Context, opts ...ValidationOption) error {
	ctx = WithValidationOptions(ctx, opts...)
	exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited
	var extras []string
	if extra := x.extra; len(extra) != 0 {
		allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed
		for _, ex := range extra {
			if allowed != nil {
				if _, ok := allowed[ex]; ok {
					continue
				}
			}
			// extras in the Extensions checked below
			if _, ok := x.Extensions[ex]; !ok {
				extras = append(extras, ex)
			}
		}
	}

	if extra := x.Extensions; exProhibited && len(extra) != 0 {
		allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed
		for ex := range extra {
			if allowed != nil {
				if _, ok := allowed[ex]; ok {
					continue
				}
			}
			extras = append(extras, ex)
		}
	}

	if len(extras) != 0 {
		return fmt.Errorf("extra sibling fields: %+v", extras)
	}

	if v := x.Value; v != nil {
		return v.Validate(ctx)
	}

	return foundUnresolvedRef(x.Ref)
}

// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable
func (x *{{ $type.Name }}Ref) JSONLookup(token string) (any, error) {
	if token == "$ref" {
		return x.Ref, nil
	}

	if v, ok := x.Extensions[token]; ok {
		return v, nil
	}

	ptr, _, err := jsonpointer.GetForToken(x.Value, token)
	return ptr, err
}
{{ end -}}
