package arxiv

import "errors"

// ErrorCode is the stable classification consumed by the arXiv Builtin
// executor.
type ErrorCode string

const (
	ErrorValidation      ErrorCode = "validation"
	ErrorNotFound        ErrorCode = "not_found"
	ErrorRateLimited     ErrorCode = "rate_limited"
	ErrorUpstreamFailure ErrorCode = "upstream_failure"
)

// Error carries a sanitized message and an internal cause.
type Error struct {
	Code    ErrorCode
	Message string
	Cause   error
}

func (err *Error) Error() string {
	if err == nil {
		return ""
	}
	return err.Message
}

func (err *Error) Unwrap() error {
	if err == nil {
		return nil
	}
	return err.Cause
}

func serviceError(code ErrorCode, message string, cause error) error {
	return &Error{Code: code, Message: message, Cause: cause}
}

// CodeOf returns a stable arXiv error code or the empty value.
func CodeOf(err error) ErrorCode {
	var typed *Error
	if errors.As(err, &typed) && typed != nil {
		return typed.Code
	}
	return ""
}
