package app

import (
	"os"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/internal/store/provider"
)

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

	sourceBytes, err := os.ReadFile("agent_messages.go")
	require.NoError(t, err)
	source := string(sourceBytes)
	sendSource := sourceFromFunctionForTest(t, source, "func (store *Store) sendAgentThreadMessageResult")
	require.Contains(t, sendSource, `coordinator.New(store.db).Run(ctx, "send agent message workflow"`)
	require.NotContains(t, sendSource, "coredb.WithTx")
}

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

	dispatcher := &serviceEventDeliveryDispatcher{
		event: serviceEventProviderWebhookEvent{
			Event: provider.ProviderEvent{
				Provider:           "github",
				EventKind:          "issue_comment",
				ActionKind:         "created",
				EventID:            "evt_1",
				ResourceIdentifier: "github:acme/agentteam#42",
				ResourceURL:        "https://github.com/acme/agentteam/pull/42",
			},
		},
	}
	candidates := []serviceEventDeliveryCandidate{
		serviceEventDeliveryGroupCandidate("sub_b", "chn_1"),
		serviceEventDeliveryGroupCandidate("sub_c", "chn_2"),
		serviceEventDeliveryGroupCandidate("sub_a", "chn_1"),
	}

	groups, err := dispatcher.groupDeliveryCandidates(candidates)
	require.NoError(t, err)
	require.Len(t, groups, 2)
	require.Equal(t, "chn_1", groups[0].Key.DeliveryScopeID)
	require.Equal(t, []string{"sub_a", "sub_b"}, serviceEventDeliveryCandidateIDs(groups[0].Candidates))
	require.Equal(t, "chn_2", groups[1].Key.DeliveryScopeID)
	require.Equal(t, []string{"sub_c"}, serviceEventDeliveryCandidateIDs(groups[1].Candidates))
	require.Equal(t, groups[0].Rendered, groups[1].Rendered)
}

func serviceEventDeliveryGroupCandidate(subscriptionID string, scopeID string) serviceEventDeliveryCandidate {
	return serviceEventDeliveryCandidate{
		Subscription: ServiceEventSubscriptionRecord{
			ID:             subscriptionID,
			WorkspaceID:    "wsp_1",
			DeliveryPolicy: pullRequestSubscriptionDeliveryPolicy,
		},
		Binding: serviceEventDeliveryTargetBinding{
			TargetKind:      "channel",
			DeliveryScopeID: strings.TrimSpace(scopeID),
		},
		ServiceEventDeliveryID: "svced_" + strings.TrimPrefix(subscriptionID, "sub_"),
	}
}
