package service

import (
	"errors"
	"fmt"
	"strings"
	"testing"

	"github.com/aws/aws-sdk-go-v2/service/athena/types"
	"github.com/stretchr/testify/require"

	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/engine"
)

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

	err := fmt.Errorf("query execution failed: %w", &engine.AthenaQueryError{
		QueryID:       "query-123",
		State:         types.QueryExecutionStateFailed,
		Reason:        "cluster 101223 failed\nreading s3://customer-bucket/path and arn:aws:glue:ap-east-1:123456789012:table/customer",
		ErrorCategory: 2,
		ErrorType:     1001,
		Retryable:     true,
	})

	diagnostics, ok := athenaQueryFailureDiagnostics(err, "101223")
	require.True(t, ok)
	require.Equal(t, "query-123", diagnostics.QueryID)
	require.Equal(t, string(types.QueryExecutionStateFailed), diagnostics.State)
	require.Equal(t, int32(2), diagnostics.Category)
	require.Equal(t, int32(1001), diagnostics.Type)
	require.True(t, diagnostics.Retryable)
	require.False(t, diagnostics.WasTruncated)
	require.Equal(t, "cluster [redacted-cluster] failed reading [redacted-location] and [redacted-aws-arn]", diagnostics.Reason)
}

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

	diagnostics, ok := athenaQueryFailureDiagnostics(&engine.AthenaQueryError{
		Reason: strings.Repeat("界", maxAthenaFailureReasonRunes+1),
	}, "")
	require.True(t, ok)
	require.True(t, diagnostics.WasTruncated)
	require.Len(t, []rune(diagnostics.Reason), maxAthenaFailureReasonRunes)

	_, ok = athenaQueryFailureDiagnostics(errors.New("not Athena"), "")
	require.False(t, ok)
	require.Nil(t, athenaQueryFailureLogFields(errors.New("not Athena"), ""))
}
