package dm

import (
	"testing"

	"github.com/pingcap/log"
	"github.com/stretchr/testify/require"
	dmpb "github.com/tidbcloud/dataflow-service/idl/pbgen/proto/dm"
)

func TestIsProcessErrEmpty(t *testing.T) {
	testCases := []struct {
		err      *dmpb.ProcessError
		expected bool
	}{
		{nil, true},
		{&dmpb.ProcessError{}, true},
		{&dmpb.ProcessError{ErrCode: 1}, false},
		{&dmpb.ProcessError{Message: "msg"}, false},
		{&dmpb.ProcessError{Workaround: "workaround"}, false},
	}

	for _, tc := range testCases {
		require.Equal(t, tc.expected, isProcessErrEmpty(tc.err))
	}
}

func TestGenProcessErrorFromDFJobError(t *testing.T) {
	raw := `failed to create dump task: http request failed, method:POST, url:https://example.com/api, response_status:400 Bad Request response_body:{
    "error_code": 10001,
    "error_msg": "[code=10001:class=database:scope=upstream:level=high], Message: database driver error, RawCause: Error 1129: Host '107.20.132.35' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts', Workaround: Please check the database connection and the database config in configuration file."
}`

	err := genProcessErrorFromDFJobError(log.L(), raw)
	require.NotNil(t, err)
	require.Equal(t, "database driver error, RawCause: Error 1129: Host '107.20.132.35' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'", err.Message)
	require.Equal(t, "Please check the database connection and the database config in configuration file.", err.Workaround)
}

func TestGenProcessErrorFromDFJobErrorFallbackForProxyEnvelope(t *testing.T) {
	raw := `failed to create dump task: http request failed, method:POST, url:https://example.com/api, response_status:400 Bad Request response_body:{invalid-json}`

	err := genProcessErrorFromDFJobError(log.L(), raw)
	require.NotNil(t, err)
	require.Equal(t, raw, err.Message)
	require.Equal(t, contactMsg, err.Workaround)
}
