package errors

import "strings"

// MultiErr is a struct that implements the error interface for consolidating multiple errors
type multiError struct {
	errs []error
}

func (e *multiError) Error() string {
	r := make([]string, 0, len(e.errs))
	for _, err := range e.errs {
		r = append(r, err.Error())
	}
	return strings.Join(r, " | ")
}

var _ error = &multiError{}

// ConsolidateErrors merges a slice of errors to a single MultiErr error
func ConsolidateErrors(errs []error) error {
	retErrs := make([]error, 0, len(errs))
	for _, err := range errs {
		if err != nil {
			if multiErr, ok := err.(*multiError); ok {
				retErrs = append(retErrs, multiErr.errs...)
			} else {
				retErrs = append(retErrs, err)
			}
		}
	}
	if len(retErrs) == 0 {
		return nil
	}
	if len(retErrs) == 1 {
		return retErrs[0]
	}
	return &multiError{
		errs: retErrs,
	}
}
