package dialectsfcrm

import (
	"errors"
	"net/http"

	"github.com/nexuscrm/dialect-sf-crm/wire"
	"github.com/nexuscrm/shared/pkg/dialect"
	sharederrors "github.com/nexuscrm/shared/pkg/errors"
)

// httpStatusError is the transitional neutral bridge for Query contract errors
// whose backend implementation still exposes generic 403/404 status categories
// without importing backend concrete types across the module seal. The dialect
// uses only the status class here; v63 wire-code ownership remains in this
// package. Prefer shared condition markers if this pattern graduates beyond the
// query relocation seam.
type httpStatusError interface {
	error
	HTTPStatus() int
}

func queryErrorResponse(status int, code string, message string) *dialect.Response {
	return &dialect.Response{Status: status, Body: wire.SFErrorResponse(code, message)}
}

func respondServiceError(req *dialect.Request, err error) *dialect.Response {
	if err == nil {
		return nil
	}
	if sharederrors.IsInternal(err) {
		return queryErrorResponse(http.StatusInternalServerError, wire.SFCodeInternalError, "An internal server error occurred. Contact your system administrator.")
	}
	var statusErr httpStatusError
	if errors.As(err, &statusErr) {
		switch statusErr.HTTPStatus() {
		case http.StatusForbidden:
			return queryErrorResponse(http.StatusForbidden, wire.SFCodeForbidden, err.Error())
		case http.StatusNotFound:
			return queryErrorResponse(http.StatusNotFound, wire.SFCodeNotFound, err.Error())
		case http.StatusConflict:
			return queryErrorResponse(http.StatusConflict, wire.SFCodeConflict, err.Error())
		}
	}
	if sfErr, status, ok := wire.SFErrorFromDomainForVersion(err, apiVersionOrDefault(req.Version)); ok {
		return &dialect.Response{Status: status, Body: []wire.SFError{sfErr}}
	}
	return nil
}
