package connector_inbound

import (
	"context"
	"testing"

	connector_workqueue "github.com/pingcap-inc/nexuscrm-connectors/features/connector/workqueue"
	contractmodels "github.com/pingcap-inc/nexuscrm-contract/pkg/models"
)

func TestFlowOutcomeFromModelPreservesTypedExecutionEvidence(t *testing.T) {
	got := FlowOutcomeFromModel(&contractmodels.FlowExecutionTypedOutcome{
		Result:      &contractmodels.FlowExecutionResult{IsSuccess: true},
		ExecutionID: "flow-execution-123",
		Cause: &contractmodels.FlowExecutionCause{
			Code:        "DB_LOCK_WAIT_TIMEOUT",
			Category:    contractmodels.FlowExecutionCauseCategoryConcurrency,
			ElementType: "ActionCall",
			ElementName: "ApplyMappings",
			Retriable:   true,
		},
	})
	if got.Result == nil || !got.Result.IsSuccess || got.ExecutionID != "flow-execution-123" || got.Cause == nil || got.Cause.Code != "DB_LOCK_WAIT_TIMEOUT" {
		t.Fatalf("FlowOutcomeFromModel = %#v, want execution id and typed cause", got)
	}
}

func TestWithFlowAttemptOutcomeCarriesPresentedAndUnderlyingCodes(t *testing.T) {
	ctx := withFlowAttemptOutcome(context.Background(), &FlowDependencyOutcome{FlowOutcome: &FlowOutcome{
		ExecutionID: "flow-execution-123",
		Result: &FlowResult{FirstError: &FlowError{
			StatusCode: "EMAIL_MALFORMED",
			Message:    "presentation only",
		}},
		Cause: &contractmodels.FlowExecutionCause{
			Code:     "DB_LOCK_WAIT_TIMEOUT",
			Category: contractmodels.FlowExecutionCauseCategoryConcurrency,
		},
	}})
	got, ok := connector_workqueue.WorkItemAttemptOutcomeFromContext(ctx)
	if !ok {
		t.Fatal("WorkItemAttemptOutcomeFromContext() ok=false, want true")
	}
	if got.FlowExecutionID != "flow-execution-123" || got.PresentedErrorCode != "EMAIL_MALFORMED" || got.Cause == nil || got.Cause.Code != "DB_LOCK_WAIT_TIMEOUT" {
		t.Fatalf("attempt outcome = %#v, want distinct presented and underlying codes", got)
	}
}
