package rewind

import (
	"context"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

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

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

	ctx := context.Background()
	db := startRewindRollbackDB(t, ctx)
	now := time.Date(2026, 5, 15, 5, 20, 0, 0, time.UTC)
	firstTouchAt := now.Add(time.Minute)
	activityAt := firstTouchAt.Add(time.Second)

	const (
		workspaceID = "wsp_rewind_scope_activity_seq"
		userID      = "usr_rewind_scope_activity_seq"
		agentID     = "agt_rewind_scope_activity_seq"
		machineID   = "mach_rewind_scope_activity_seq"
		humanMember = "mem_rewind_scope_activity_human"
		agentMember = "mem_rewind_scope_activity_agent"
		rewindScope = "scp_rewind_scope_activity_target"
		otherScope  = "scp_rewind_scope_activity_other"
		activityID  = "act_rewind_scope_activity_other"
		reactionID  = "react_rewind_scope_activity_other"
	)

	mustExecRecovery(t, db, `
INSERT INTO users (id, email, name, display_name, avatar_url, is_admin, password_hash, email_verified_at, created_at, updated_at)
VALUES ($1, CONCAT($1, '@example.com'), $1, $1, '', FALSE, 'hash', $2, $2, $2)
`, userID, now)
	mustExecRecovery(t, db, `
INSERT INTO workspaces (id, organization_id, slug, name, latest_message_seq, created_at, updated_at)
VALUES ($1, $2, $1, $1, 0, $3, $3)
`, workspaceID, testfixture.SeedWorkspaceOrganization(t, ctx, db, workspaceID, now), now)
	mustExecRecovery(t, db, `
INSERT INTO members (id, workspace_id, type, display_name, user_id, workspace_role, created_at, updated_at)
VALUES ($1, $2, 'human', $1, $3, 'member', $4, $4)
`, humanMember, workspaceID, userID, now)
	seedRewindAgentMember(t, ctx, db, workspaceID, userID, agentID, machineID, agentMember, now)
	mustExecRecovery(t, db, `
INSERT INTO scopes (id, workspace_id, type, identity_key, latest_seq, latest_global_seq, latest_activity_seq, latest_message_at, archived_until_seq, status, created_at, updated_at)
VALUES
  ($1, $3, 'channel', CONCAT('channel:', $1), 0, 0, 0, NULL, 0, 'active', $4, $4),
  ($2, $3, 'channel', CONCAT('channel:', $2), 0, 0, 1, NULL, 0, 'active', $4, $4)
`, rewindScope, otherScope, workspaceID, now)
	mustExecRecovery(t, db, `
INSERT INTO scope_activity_events (
  id, workspace_id, scope_id, seq, activity_type, activity_ref_type, activity_ref_id,
  activity_global_seq, actor_member_id, reason, created_at
) VALUES (
  $1, $2, $3, 1, 'reaction_created', 'reaction', $4,
  1, $5, '', $6
)
`, activityID, workspaceID, otherScope, reactionID, agentMember, activityAt)

	conflicted, err := AgentHasCrossScopeActivityAfterExcluding(ctx, db, workspaceID, agentID, []string{rewindScope}, firstTouchAt)
	require.NoError(t, err)
	require.True(t, conflicted, "post-first-touch activity in another scope must be detected even when activity_global_seq is only a scope-local compatibility alias")
}
