package workflow

import (
	"errors"
	"fmt"
	"strings"
)

const terminalErrorMarker = "[[workflow-terminal:v1]]"

// TerminalError marks an error which cannot be repaired by replaying the task.
// The marker is intentionally part of Error() because FastFlow persists the
// rendered error string in TaskInstance.Reason.
type TerminalError struct {
	Err error
}

func (e *TerminalError) Error() string {
	if e.Err == nil {
		return terminalErrorMarker + " terminal"
	}
	return fmt.Sprintf("%s %s", terminalErrorMarker, e.Err)
}

func (e *TerminalError) Unwrap() error { return e.Err }

func NewTerminalError(err error) error {
	if err == nil {
		return nil
	}
	return &TerminalError{Err: err}
}

func IsTerminalError(err error) bool {
	var terminalErr *TerminalError
	return errors.As(err, &terminalErr)
}

func IsTerminalReason(reason string) bool {
	return strings.Contains(reason, terminalErrorMarker)
}
