/*
Copyright 2014 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package field

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"

	utilerrors "k8s.io/apimachinery/pkg/util/errors"
	"k8s.io/apimachinery/pkg/util/sets"
)

// Error is an implementation of the 'error' interface, which represents a
// field-level validation error.
type Error struct {
	Type     ErrorType
	Field    string
	BadValue interface{}
	Detail   string

	// Origin uniquely identifies where this error was generated from. It is used in testing to
	// compare expected errors against actual errors without relying on exact detail string matching.
	// This allows tests to verify the correct validation logic triggered the error
	// regardless of how the error message might be formatted or localized.
	//
	// The value should be either:
	// - A simple camelCase identifier (e.g., "maximum", "maxItems")
	// - A structured format using "format=<dash-style-identifier>" for validation errors related to specific formats
	//   (e.g. "format=k8s-short-name")
	//
	// If the Origin corresponds to an existing declarative validation tag or JSON Schema keyword,
	// use that same name for consistency.
	//
	// Origin should be set in the most deeply nested validation function that
	// can still identify the unique source of the error.
	Origin string

	// CoveredByDeclarative is true when this error is covered by declarative
	// validation. This field is to identify errors from imperative validation
	// that should also be caught by declarative validation.
	CoveredByDeclarative bool

	// FromImperative denotes these errors are originating from  the hand written validations.
	FromImperative bool

	// ValidationStabilityLevel denotes the validation stability level of the declarative validation from this error is returned. This should be used in the declarative validations only.
	ValidationStabilityLevel ValidationStabilityLevel
}

// ValidationStabilityLevel denotes the stability level of a validation.
type ValidationStabilityLevel int

const (
	stabilityLevelUnknown ValidationStabilityLevel = iota
	stabilityLevelAlpha
	stabilityLevelBeta
)

func (v ValidationStabilityLevel) String() string {
	switch v {
	case stabilityLevelAlpha:
		return "alpha"
	case stabilityLevelBeta:
		return "beta"
	default:
		return "unknown"
	}
}

var _ error = &Error{}

// IsAlpha returns true if the error is an alpha validation error.
func (e *Error) IsAlpha() bool {
	return e.ValidationStabilityLevel == stabilityLevelAlpha
}

// IsBeta returns true if the error is a beta validation error.
func (e *Error) IsBeta() bool {
	return e.ValidationStabilityLevel == stabilityLevelBeta
}

// Error implements the error interface.
func (e *Error) Error() string {
	return fmt.Sprintf("%s: %s", e.Field, e.ErrorBody())
}

type OmitValueType struct{}

var omitValue = OmitValueType{}

// ErrorBody returns the error message without the field name.  This is useful
// for building nice-looking higher-level error reporting.
func (e *Error) ErrorBody() string {
	var s string
	switch e.Type {
	case ErrorTypeRequired, ErrorTypeForbidden, ErrorTypeTooLong, ErrorTypeTooShort, ErrorTypeInternal:
		s = e.Type.String()
	case ErrorTypeInvalid, ErrorTypeTypeInvalid, ErrorTypeNotSupported,
		ErrorTypeNotFound, ErrorTypeDuplicate, ErrorTypeTooMany, ErrorTypeTooFew:
		if e.BadValue == omitValue {
			s = e.Type.String()
			break
		}
		switch t := e.BadValue.(type) {
		case int64, int32, float64, float32, bool:
			// use simple printer for simple types
			s = fmt.Sprintf("%s: %v", e.Type, t)
		case string:
			s = fmt.Sprintf("%s: %q", e.Type, t)
		default:
			// use more complex techniques to render more complex types
			valstr := ""
			jb, err := json.Marshal(e.BadValue)
			if err == nil {
				// best case
				valstr = string(jb)
			} else if stringer, ok := e.BadValue.(fmt.Stringer); ok {
				// anything that defines String() is better than raw struct
				valstr = stringer.String()
			} else {
				// worst case - fallback to raw struct
				// TODO: internal types have panic guards against json.Marshalling to prevent
				// accidental use of internal types in external serialized form.  For now, use
				// %#v, although it would be better to show a more expressive output in the future
				valstr = fmt.Sprintf("%#v", e.BadValue)
			}
			s = fmt.Sprintf("%s: %s", e.Type, valstr)
		}
	default:
		internal := InternalError(nil, fmt.Errorf("unhandled error code: %s: please report this", e.Type))
		s = internal.ErrorBody()
	}
	if len(e.Detail) != 0 {
		s += fmt.Sprintf(": %s", e.Detail)
	}

	return s
}

// WithOrigin adds origin information to the FieldError
func (e *Error) WithOrigin(o string) *Error {
	e.Origin = o
	return e
}

// MarkCoveredByDeclarative marks the error as covered by declarative validation.
func (e *Error) MarkCoveredByDeclarative() *Error {
	e.CoveredByDeclarative = true
	return e
}

// ErrorType is a machine readable value providing more detail about why
// a field is invalid.  These values are expected to match 1-1 with
// CauseType in api/types.go.
type ErrorType string

// TODO: These values are duplicated in api/types.go, but there's a circular dep.  Fix it.
const (
	// ErrorTypeNotFound is used to report failure to find a requested value
	// (e.g. looking up an ID).  See NotFound().
	ErrorTypeNotFound ErrorType = "FieldValueNotFound"
	// ErrorTypeRequired is used to report required values that are not
	// provided (e.g. empty strings, null values, or empty arrays).  See
	// Required().
	ErrorTypeRequired ErrorType = "FieldValueRequired"
	// ErrorTypeDuplicate is used to report collisions of values that must be
	// unique (e.g. unique IDs).  See Duplicate().
	ErrorTypeDuplicate ErrorType = "FieldValueDuplicate"
	// ErrorTypeInvalid is used to report malformed values (e.g. failed regex
	// match, too long, out of bounds).  See Invalid().
	ErrorTypeInvalid ErrorType = "FieldValueInvalid"
	// ErrorTypeNotSupported is used to report unknown values for enumerated
	// fields (e.g. a list of valid values).  See NotSupported().
	ErrorTypeNotSupported ErrorType = "FieldValueNotSupported"
	// ErrorTypeForbidden is used to report valid (as per formatting rules)
	// values which would be accepted under some conditions, but which are not
	// permitted by the current conditions (such as security policy).  See
	// Forbidden().
	ErrorTypeForbidden ErrorType = "FieldValueForbidden"
	// ErrorTypeTooLong is used to report that the given value is too long.
	// This is similar to ErrorTypeInvalid, but the error will not include the
	// too-long value.  See TooLong().
	ErrorTypeTooLong ErrorType = "FieldValueTooLong"
	// ErrorTypeTooMany is used to report "too many". This is used to
	// report that a given list has too many items. This is similar to FieldValueTooLong,
	// but the error indicates quantity instead of length.
	ErrorTypeTooMany ErrorType = "FieldValueTooMany"
	// ErrorTypeTooFew is used to report "too few". This is used to
	// report that a given list has too few items. This is similar to FieldValueTooLong,
	// but the error indicates quantity instead of length.
	ErrorTypeTooFew ErrorType = "FieldValueTooFew"
	// ErrorTypeInternal is used to report other errors that are not related
	// to user input.  See InternalError().
	ErrorTypeInternal ErrorType = "InternalError"
	// ErrorTypeTypeInvalid is for the value did not match the schema type for that field
	ErrorTypeTypeInvalid ErrorType = "FieldValueTypeInvalid"
	// ErrorTypeTooShort is used to report that the given value is too short.
	// This is similar to ErrorTypeInvalid. See TooShort().
	ErrorTypeTooShort ErrorType = "FieldValueTooShort"
)

// String converts a ErrorType into its corresponding canonical error message.
func (t ErrorType) String() string {
	switch t {
	case ErrorTypeNotFound:
		return "Not found"
	case ErrorTypeRequired:
		return "Required value"
	case ErrorTypeDuplicate:
		return "Duplicate value"
	case ErrorTypeInvalid:
		return "Invalid value"
	case ErrorTypeNotSupported:
		return "Unsupported value"
	case ErrorTypeForbidden:
		return "Forbidden"
	case ErrorTypeTooLong:
		return "Too long"
	case ErrorTypeTooMany:
		return "Too many"
	case ErrorTypeTooFew:
		return "Too few"
	case ErrorTypeInternal:
		return "Internal error"
	case ErrorTypeTypeInvalid:
		return "Invalid value"
	case ErrorTypeTooShort:
		return "Too short"
	default:
		return fmt.Sprintf("<unknown error %q>", string(t))
	}
}

// TypeInvalid returns a *Error indicating "type is invalid"
func TypeInvalid(field *Path, value interface{}, detail string) *Error {
	return &Error{
		Type:     ErrorTypeTypeInvalid,
		Field:    field.String(),
		BadValue: value,
		Detail:   detail,
	}
}

// NotFound returns a *Error indicating "value not found".  This is
// used to report failure to find a requested value (e.g. looking up an ID).
func NotFound(field *Path, value interface{}) *Error {
	return &Error{
		Type:     ErrorTypeNotFound,
		Field:    field.String(),
		BadValue: value,
	}
}

// Required returns a *Error indicating "value required".  This is used
// to report required values that are not provided (e.g. empty strings, null
// values, or empty arrays).
func Required(field *Path, detail string) *Error {
	return &Error{
		Type:     ErrorTypeRequired,
		Field:    field.String(),
		Detail:   detail,
		BadValue: "",
	}
}

// Duplicate returns a *Error indicating "duplicate value".  This is
// used to report collisions of values that must be unique (e.g. names or IDs).
func Duplicate(field *Path, value interface{}) *Error {
	return &Error{
		Type:     ErrorTypeDuplicate,
		Field:    field.String(),
		BadValue: value,
	}
}

// Invalid returns a *Error indicating "invalid value".  This is used
// to report malformed values (e.g. failed regex match, too long, out of bounds).
func Invalid(field *Path, value interface{}, detail string) *Error {
	return &Error{
		Type:     ErrorTypeInvalid,
		Field:    field.String(),
		BadValue: value,
		Detail:   detail,
	}

}

// NotSupported returns a *Error indicating "unsupported value".
// This is used to report unknown values for enumerated fields (e.g. a list of
// valid values).
func NotSupported[T ~string](field *Path, value interface{}, validValues []T) *Error {
	detail := ""
	if len(validValues) > 0 {
		quotedValues := make([]string, len(validValues))
		for i, v := range validValues {
			quotedValues[i] = strconv.Quote(fmt.Sprint(v))
		}
		detail = "supported values: " + strings.Join(quotedValues, ", ")
	}
	return &Error{
		Type:     ErrorTypeNotSupported,
		Field:    field.String(),
		BadValue: value,
		Detail:   detail,
	}
}

// Forbidden returns a *Error indicating "forbidden".  This is used to
// report valid (as per formatting rules) values which would be accepted under
// some conditions, but which are not permitted by current conditions (e.g.
// security policy).
func Forbidden(field *Path, detail string) *Error {
	return &Error{
		Type:     ErrorTypeForbidden,
		Field:    field.String(),
		Detail:   detail,
		BadValue: "",
	}
}

// TooLong returns a *Error indicating "too long".  This is used to report that
// the given value is too long.  This is similar to Invalid, but the returned
// error will not include the too-long value. If maxLength is negative, it will
// be included in the message.  The value argument is not used.
func TooLong(field *Path, _ interface{}, maxLength int) *Error {
	var msg string
	if maxLength >= 0 {
		bs := "bytes"
		if maxLength == 1 {
			bs = "byte"
		}
		msg = fmt.Sprintf("may not be more than %d %s", maxLength, bs)
	} else {
		msg = "value is too long"
	}
	return &Error{
		Type:     ErrorTypeTooLong,
		Field:    field.String(),
		BadValue: "<value omitted>",
		Detail:   msg,
	}
}

// TooLongCharacters returns a *Error indicating "too long".  This is used to report that
// the given value is too long in characters (including multi-byte characters).
// This is similar to Invalid, but the returned  error will not include the too-long value.
// If maxLength is negative, it will be included in the message. The value argument is not used.
func TooLongCharacters[T ~string](field *Path, _ T, maxLength int) *Error {
	var msg string
	if maxLength >= 0 {
		bs := "characters"
		if maxLength == 1 {
			bs = "character"
		}
		msg = fmt.Sprintf("may not be more than %d %s", maxLength, bs)
	} else {
		msg = "value is too long"
	}
	return &Error{
		Type:     ErrorTypeTooLong,
		Field:    field.String(),
		BadValue: "<value omitted>",
		Detail:   msg,
	}
}

// TooLongMaxLength returns a *Error indicating "too long".
// Deprecated: Use TooLong instead.
func TooLongMaxLength(field *Path, value interface{}, maxLength int) *Error {
	return TooLong(field, "", maxLength)
}

// TooMany returns a *Error indicating "too many". This is used to
// report that a given list has too many items. This is similar to TooLong,
// but the returned error indicates quantity instead of length.
func TooMany(field *Path, actualQuantity, maxQuantity int) *Error {
	var msg string

	if maxQuantity >= 0 {
		is := "items"
		if maxQuantity == 1 {
			is = "item"
		}
		msg = fmt.Sprintf("must have at most %d %s", maxQuantity, is)
	} else {
		msg = "has too many items"
	}

	var actual interface{}
	if actualQuantity >= 0 {
		actual = actualQuantity
	} else {
		actual = omitValue
	}

	return &Error{
		Type:     ErrorTypeTooMany,
		Field:    field.String(),
		BadValue: actual,
		Detail:   msg,
	}
}

// InternalError returns a *Error indicating "internal error".  This is used
// to signal that an error was found that was not directly related to user
// input.  The err argument must be non-nil.
func InternalError(field *Path, err error) *Error {
	return &Error{
		Type:     ErrorTypeInternal,
		Field:    field.String(),
		BadValue: err,
		Detail:   err.Error(),
	}
}

// TooShort returns a *Error indicating "too short".  This is used to report that
// the given value is too short in characters. This is similar to Invalid.
// If minLength is non-negative, it will  be included in the message.
func TooShort[T ~string](field *Path, value T, minLength int) *Error {
	var msg string
	if minLength >= 0 {
		bs := "characters"
		if minLength == 1 {
			bs = "character"
		}
		msg = fmt.Sprintf("must be at least %d %s", minLength, bs)
	} else {
		msg = "value is too short"
	}
	return &Error{
		Type:     ErrorTypeTooShort,
		Field:    field.String(),
		BadValue: value,
		Detail:   msg,
	}
}

// ErrorList holds a set of Errors.  It is plausible that we might one day have
// non-field errors in this same umbrella package, but for now we don't, so
// we can keep it simple and leave ErrorList here.
type ErrorList []*Error

// NewErrorTypeMatcher returns an errors.Matcher that returns true
// if the provided error is a Error and has the provided ErrorType.
func NewErrorTypeMatcher(t ErrorType) utilerrors.Matcher {
	return func(err error) bool {
		if e, ok := err.(*Error); ok {
			return e.Type == t
		}
		return false
	}
}

// WithOrigin sets the origin for all errors in the list and returns the updated list.
func (list ErrorList) WithOrigin(origin string) ErrorList {
	for _, err := range list {
		err.Origin = origin
	}
	return list
}

// MarkCoveredByDeclarative marks all errors in the list as covered by declarative validation.
func (list ErrorList) MarkCoveredByDeclarative() ErrorList {
	for _, err := range list {
		err.CoveredByDeclarative = true
	}
	return list
}

// PrefixDetail adds a prefix to the Detail for all errors in the list and returns the updated list.
func (list ErrorList) PrefixDetail(prefix string) ErrorList {
	for _, err := range list {
		err.Detail = prefix + err.Detail
	}
	return list
}

// ToAggregate converts the ErrorList into an errors.Aggregate.
func (list ErrorList) ToAggregate() utilerrors.Aggregate {
	if len(list) == 0 {
		return nil
	}
	errs := make([]error, 0, len(list))
	errorMsgs := sets.NewString()
	for _, err := range list {
		msg := fmt.Sprintf("%v", err)
		if errorMsgs.Has(msg) {
			continue
		}
		errorMsgs.Insert(msg)
		errs = append(errs, err)
	}
	return utilerrors.NewAggregate(errs)
}

func fromAggregate(agg utilerrors.Aggregate) ErrorList {
	errs := agg.Errors()
	list := make(ErrorList, len(errs))
	for i := range errs {
		list[i] = errs[i].(*Error)
	}
	return list
}

// Filter removes items from the ErrorList that match the provided fns.
func (list ErrorList) Filter(fns ...utilerrors.Matcher) ErrorList {
	err := utilerrors.FilterOut(list.ToAggregate(), fns...)
	if err == nil {
		return nil
	}
	// FilterOut takes an Aggregate and returns an Aggregate
	return fromAggregate(err.(utilerrors.Aggregate))
}

// ExtractCoveredByDeclarative returns a new ErrorList containing only the errors that should be covered by declarative validation.
func (list ErrorList) ExtractCoveredByDeclarative() ErrorList {
	newList := ErrorList{}
	for _, err := range list {
		if err.CoveredByDeclarative {
			newList = append(newList, err)
		}
	}
	return newList
}

// MarkAlpha marks the error as an alpha validation error.
func (e *Error) MarkAlpha() *Error {
	e.ValidationStabilityLevel = stabilityLevelAlpha
	return e
}

// MarkAlpha marks the errors as alpha validation errors.
func (list ErrorList) MarkAlpha() ErrorList {
	for _, err := range list {
		err.ValidationStabilityLevel = stabilityLevelAlpha
	}
	return list
}

// MarkBeta marks the error as a beta validation error.
func (e *Error) MarkBeta() *Error {
	e.ValidationStabilityLevel = stabilityLevelBeta
	return e
}

// MarkBeta marks the errors as beta validation errors.
func (list ErrorList) MarkBeta() ErrorList {
	for _, err := range list {
		err.ValidationStabilityLevel = stabilityLevelBeta
	}
	return list
}

func (e *Error) MarkFromImperative() *Error {
	e.FromImperative = true
	return e
}

func (list ErrorList) MarkFromImperative() ErrorList {
	for _, err := range list {
		err.FromImperative = true
	}
	return list
}

// RemoveCoveredByDeclarative returns a new ErrorList containing only the errors that should not be covered by declarative validation.
func (list ErrorList) RemoveCoveredByDeclarative() ErrorList {
	newList := ErrorList{}
	for _, err := range list {
		if !err.CoveredByDeclarative {
			newList = append(newList, err)
		}
	}
	return newList
}

// TooFew returns a *Error indicating "too few". This is used to
// report that a given list has too few items. This is similar to TooLong,
// but the returned error indicates quantity instead of length.
func TooFew(field *Path, actualQuantity, minQuantity int) *Error {
	var msg string

	if minQuantity >= 0 {
		is := "items"
		if minQuantity == 1 {
			is = "item"
		}
		msg = fmt.Sprintf("must have at least %d %s", minQuantity, is)
	} else {
		msg = "has too few items"
	}

	return &Error{
		Type:     ErrorTypeTooFew,
		Field:    field.String(),
		BadValue: actualQuantity,
		Detail:   msg,
	}
}
