package error

import (
	stderrors "errors"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestClassifiedErrorWrapPreservesCause(t *testing.T) {
	t.Parallel()

	cause := stderrors.New("dial tcp: connection refused")
	err := WrapConnection(cause)

	require.ErrorIs(t, err, cause)
	require.True(t, IsConnection(err))
	require.False(t, IsStorage(err))
	require.False(t, IsService(err))

	classified, ok := stderrors.AsType[*ClassifiedError](err)
	require.True(t, ok)
	require.Equal(t, ClassConnection, classified.Class())
}

func TestClassifiedErrorDoesNotDoubleWrapSameClass(t *testing.T) {
	t.Parallel()

	cause := stderrors.New("write file")
	first := WrapStorage(cause)
	second := WrapStorage(first)

	require.Same(t, first, second)
}

func TestGenericErrorSupportsAsAndUnwrap(t *testing.T) {
	t.Parallel()

	cause := stderrors.New("root cause")
	err := newGenericError(ErrDummy, cause, "subject")

	require.ErrorIs(t, err, cause)

	generic, ok := stderrors.AsType[*GenericError](err)
	require.True(t, ok)
	require.Equal(t, ErrDummy, generic.Code)
	require.Equal(t, "Dummy: subject: root cause", err.Error())
}
