package derrs

import "errors"

func CollectErrors[T error](err error) []T {
	var result []T

	var visit func(error)
	visit = func(e error) {
		switch v := e.(type) {
		case interface{ Unwrap() []error }:
			for _, ue := range v.Unwrap() {
				visit(ue)
			}
		default:
			var t T
			if errors.As(e, &t) {
				result = append(result, t)
			}
		}
	}

	if err != nil {
		visit(err)
	}

	return result
}

func Contains(err error, code Code) bool {
	errs := CollectErrors[*Error](err)
	for _, e := range errs {
		if e.code == code {
			return true
		}
	}
	return false
}
