package placement

import (
	"context"
	"fmt"
	"strings"

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

func keywordSearchViaThreadsAPI(ctx context.Context, req DiscoverRequest) ([]DiscoverPost, error) {
	token := strings.TrimSpace(req.Member.ThreadsAPIAccessToken)
	if token == "" {
		return nil, fmt.Errorf("threads api access token not configured for active account")
	}

	client := libthreads.NewClient(token)
	searchType := "TOP"
	if req.Recency {
		searchType = "RECENT"
	}
	limit := req.Limit
	if limit <= 0 {
		limit = 12
	}

	// Strip site: prefix for API keyword search.
	query := strings.TrimSpace(req.Query)
	query = strings.TrimPrefix(query, "site:threads.net ")
	query = strings.Trim(query, `"`)
	if idx := strings.Index(query, " after:"); idx > 0 {
		query = strings.TrimSpace(query[:idx])
	}
	query = strings.Trim(query, `"`)

	items, err := client.KeywordSearch(ctx, libthreads.KeywordSearchOptions{
		Query:      query,
		Limit:      limit,
		SearchType: searchType,
	})
	if err != nil {
		return nil, err
	}

	out := make([]DiscoverPost, 0, len(items))
	for _, item := range items {
		text := strings.TrimSpace(item.Text)
		if text == "" {
			continue
		}
		permalink := strings.TrimSpace(item.Permalink)
		if permalink == "" && item.Username != "" && item.ID != "" {
			permalink = "https://www.threads.net/@" + item.Username + "/post/" + item.ID
		}
		out = append(out, DiscoverPost{
			Text:       text,
			Permalink:  permalink,
			ExternalID: strings.TrimSpace(item.ID),
			Author:     strings.TrimSpace(item.Username),
			PostedAt:   strings.TrimSpace(item.Timestamp),
			LikeCount:  item.LikeCount,
			ReplyCount: item.ReplyCount,
			Source:     DiscoverThreadsAPI,
		})
	}
	return out, nil
}
