package repo_imp

import (
	"testing"

	"github.com/stretchr/testify/require"
	"github.com/tidbcloud/serverless-service/internal/domain/constant"
)

func TestShouldRefreshFailedTime(t *testing.T) {
	tests := []struct {
		name             string
		currentState     constant.ChangfeedState
		currentError     string
		nextState        constant.ChangfeedState
		nextError        string
		expectNeedUpdate bool
	}{
		{
			name:             "keep failed_time when nil and state/error unchanged",
			currentState:     constant.ChangefeedStateFailed,
			currentError:     "same",
			nextState:        constant.ChangefeedStateFailed,
			nextError:        "same",
			expectNeedUpdate: false,
		},
		{
			name:             "refresh when state changes",
			currentState:     constant.ChangefeedStateWarning,
			currentError:     "same",
			nextState:        constant.ChangefeedStateFailed,
			nextError:        "same",
			expectNeedUpdate: true,
		},
		{
			name:             "refresh when only error changes",
			currentState:     constant.ChangefeedStateFailed,
			currentError:     "old-error",
			nextState:        constant.ChangefeedStateFailed,
			nextError:        "new-error",
			expectNeedUpdate: true,
		},
		{
			name:             "keep failed_time when state and error unchanged",
			currentState:     constant.ChangefeedStateFailed,
			currentError:     "same",
			nextState:        constant.ChangefeedStateFailed,
			nextError:        "same",
			expectNeedUpdate: false,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			needUpdate := shouldRefreshFailedTime(
				tc.currentState,
				tc.currentError,
				tc.nextState,
				tc.nextError,
			)
			require.Equal(t, tc.expectNeedUpdate, needUpdate)
		})
	}
}
