package message

import (
	"sort"
	"strings"

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

func NormalizeReplyThreadParticipantIDs(participantIDs []string) []string {
	if len(participantIDs) == 0 {
		return []string{}
	}

	normalized := make([]string, 0, len(participantIDs))
	seen := make(map[string]struct{}, len(participantIDs))
	for _, participantID := range participantIDs {
		trimmed := strings.TrimSpace(participantID)
		if trimmed == "" {
			continue
		}
		if _, ok := seen[trimmed]; ok {
			continue
		}
		seen[trimmed] = struct{}{}
		normalized = append(normalized, trimmed)
	}
	sort.Strings(normalized)
	return normalized
}

func MergeReplyThreadParticipantIDs(current []string, additions []string) []string {
	merged := make([]string, 0, len(current)+len(additions))
	merged = append(merged, current...)
	merged = append(merged, additions...)
	return NormalizeReplyThreadParticipantIDs(merged)
}

func MarshalReplyThreadParticipantIDs(participantIDs []string) ([]byte, error) {
	return model.MarshalJSONObject("reply thread participant ids", NormalizeReplyThreadParticipantIDs(participantIDs))
}
