package records

import appErrors "github.com/nexuscrm/kernel/pkg/errors"

// clientValidationErrorCollector combines independent client-visible
// validation failures by default. An explicit compatibility opt-out keeps the
// legacy fail-fast behavior available to isolated callers. Unclassified and
// internal errors remain terminal so aggregation cannot hide an authority or
// IO fault.
type clientValidationErrorCollector struct {
	enabled bool
	errors  []error
}

func (ps *PersistenceService) newClientValidationErrorCollector() *clientValidationErrorCollector {
	return &clientValidationErrorCollector{
		enabled: ps != nil && ps.validator != nil && ps.validator.CollectAllValidationErrorsEnabled(),
	}
}

func (c *clientValidationErrorCollector) add(err error) error {
	if err == nil {
		return nil
	}
	if c == nil || !c.enabled {
		return err
	}
	typed, ok := appErrors.AsClientValidationError(err)
	if !ok {
		return err
	}
	if _, ok := appErrors.AsClientValidationErrors(typed); !ok {
		return err
	}
	c.errors = append(c.errors, typed)
	return nil
}

func (c *clientValidationErrorCollector) combined() error {
	if c == nil {
		return nil
	}
	return appErrors.NewClientValidationErrors(c.errors...)
}
