package dialectsfcrm

import (
	"fmt"
	"net/http"

	sharederrors "github.com/nexuscrm/shared/pkg/errors"
)

// ValidationError is the module-local port of backend/pkg/errors.ValidationError.
//
// TRANSITIONAL DUPLICATION (named — see doc.go): the canonical type lives in
// backend/pkg/errors. This module CANNOT import it: backend/pkg/errors has the
// module path prefix github.com/nexuscrm/backend, which the seal (seal_test.go)
// forbids by HasPrefix. (It is NOT a dependency-cycle problem — backend/pkg/errors'
// own closure is shared + stdlib only — purely the forbidden module path.) Only
// Field + Message are wire-load-bearing for the composite/tree route's validation
// envelope; this minimal port reproduces exactly those plus the AppError surface
// (HTTPStatus/Code) so errors.As against *ValidationError behaves identically to the
// backend guard path.
//
// Death condition: collapses when the validation-error envelope + v63 wire codec are
// extracted to a shared-only L1 surface (a later #1715/#2015 step) and both backend
// and this module read it through one path.
type ValidationError struct {
	Field   string
	Message string
	Value   any
}

func (e *ValidationError) Error() string {
	if e.Field != "" {
		return fmt.Sprintf("validation error on field '%s': %s", e.Field, e.Message)
	}
	return fmt.Sprintf("validation error: %s", e.Message)
}

func (e *ValidationError) HTTPStatus() int { return http.StatusBadRequest }

// Code mirrors backend/pkg/errors.ValidationError.Code(): it resolves through the
// shared error-code SSoT (shared IS allowed across the seal). It is off the wire
// path for this route (the v63 envelope uses Field+Message only) but kept for
// faithful parity.
func (e *ValidationError) Code() string { return string(sharederrors.ErrValidation) }

func (e *ValidationError) ValidationField() string {
	if e == nil {
		return ""
	}
	return e.Field
}

func (e *ValidationError) ValidationMessage() string {
	if e == nil {
		return ""
	}
	return e.Message
}

// NewValidationError mirrors backend/pkg/errors.NewValidationError.
func NewValidationError(field, message string) *ValidationError {
	return &ValidationError{Field: field, Message: message}
}
