package placement

import (
	"context"
	"strings"

	libthreads "haixun-backend/internal/library/threadsapi"
)

// PreferReplyExternalID keeps a numeric Threads media id when merging scan rows.
func PreferReplyExternalID(existing, incoming string) string {
	a := strings.TrimSpace(existing)
	b := strings.TrimSpace(incoming)
	if libthreads.IsNumericMediaID(a) {
		return a
	}
	if libthreads.IsNumericMediaID(b) {
		return b
	}
	if b != "" {
		return b
	}
	return a
}

// EnrichDiscoverPostsMediaIDs resolves shortcode-only crawler rows via Threads API when possible.
func EnrichDiscoverPostsMediaIDs(ctx context.Context, accessToken string, posts []DiscoverPost) []DiscoverPost {
	token := strings.TrimSpace(accessToken)
	if token == "" || len(posts) == 0 {
		return posts
	}
	client := libthreads.NewClient(token)
	out := make([]DiscoverPost, len(posts))
	copy(out, posts)
	for i := range out {
		if libthreads.IsNumericMediaID(out[i].ExternalID) {
			continue
		}
		id, err := client.ResolveReplyMedia(ctx, libthreads.ResolveReplyMediaInput{
			ExternalID: out[i].ExternalID,
			Permalink:  out[i].Permalink,
			HintText:   out[i].Text,
		})
		if err != nil || !libthreads.IsNumericMediaID(id) {
			continue
		}
		out[i].ExternalID = id
	}
	return out
}
