package testkit

import (
	"context"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/internal/coredb"
	"github.com/tidbcloud/AgentTeam/internal/store/message"
)

// MakeAgentPublicChannelParticipant force-aligns an integration-test agent with
// the public-channel membership shape. It writes the canonical scope membership
// and notification setting for the requested channel, then returns the agent's
// member ID.
func MakeAgentPublicChannelParticipant(t *testing.T, ctx context.Context, db coredb.DB, workspaceID string, channelID string, agentID string) string {
	t.Helper()

	var agentMemberID string
	require.NoError(t, db.QueryRow(ctx, `
SELECT member_id
FROM agents
WHERE workspace_id = $1 AND id = $2
`, workspaceID, agentID).Scan(&agentMemberID))
	require.NotEmpty(t, agentMemberID)

	now := time.Now().UTC()
	require.NoError(t, message.EnsureScopeMembership(ctx, db, channelID, agentMemberID, "public", "", "auto-wake", 0, 0, now))

	return agentMemberID
}

// MakeAgentPublicChannelParticipantForAppTest force-aligns an integration-test
// agent with the public-channel participant shape used by HTTP/API fixtures.
// It is kept in testkit so migrated external API packages can share the setup
// without depending on package-local helpers.
func MakeAgentPublicChannelParticipantForAppTest(t *testing.T, runtime Runtime, workspaceID string, channelID string, agentID string) string {
	t.Helper()

	return MakeAgentPublicChannelParticipant(t, runtime.Ctx, runtime.Pool, workspaceID, channelID, agentID)
}
