package message

import (
	"context"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
)

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

	ctx := context.Background()
	db := startMessagingTestPool(t, ctx)
	now := time.Date(2026, 6, 16, 16, 0, 0, 0, time.UTC)
	fixture := seedConversationListFixture(t, ctx, db, "duplicate_thread_parent_membership", now)
	mustExecMessaging(t, ctx, db, `
INSERT INTO scope_memberships (
    scope_id, member_id, visibility, owner_member_id, last_read_seq,
    last_read_global_seq, last_activity_global_seq, owner_context_dismissed_through_global_seq,
    effective_from_seq, effective_to_seq, created_at, updated_at, removed_at, archived_at
)
VALUES ($1, $2, 'public', NULL, 0, 0, 0, 0, 1, NULL, $3, $3, NULL, NULL)
`, fixture.channelID, fixture.ownerMemberID, now.Add(5*time.Minute))

	store := New(db, nil, 0, Options{})
	page, err := store.ListConversationsForUserFiltered(ctx, fixture.ownerUserID, fixture.workspaceID, 10, ConversationCursor{}, ConversationKindFilter{Kinds: []string{"replyThread"}})
	require.NoError(t, err)
	require.Equal(t, []string{fixture.threadID}, conversationScopeIDsForTest(page.Items))
}
