package threads_account

import (
	"context"
	"fmt"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	libthreads "haixun-backend/internal/library/threadsapi"
	libviral "haixun-backend/internal/library/viral"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

type SearchContentFormulaPostsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSearchContentFormulaPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchContentFormulaPostsLogic {
	return &SearchContentFormulaPostsLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *SearchContentFormulaPostsLogic) SearchContentFormulaPosts(req *types.SearchContentFormulaPostsHandlerReq) (*types.SearchContentFormulaPostsData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	keyword := strings.TrimSpace(req.Keyword)
	if keyword == "" {
		return nil, app.For(code.ThreadsAccount).InputMissingRequired("keyword is required")
	}
	if _, err := l.svcCtx.ThreadsAccount.Get(l.ctx, tenantID, uid, req.ID); err != nil {
		return nil, err
	}
	token, err := l.svcCtx.ThreadsAccount.ResolveAccountAPIAccessToken(l.ctx, tenantID, uid, req.ID)
	if err != nil {
		return nil, err
	}
	client := libthreads.NewClient(token)
	if !client.Enabled() {
		return nil, app.For(code.ThreadsAccount).InputMissingRequired("Threads API 未連線")
	}
	limit := req.Limit
	if limit <= 0 {
		limit = 10
	}
	searchType := strings.TrimSpace(req.SearchType)
	if searchType == "" {
		searchType = "TOP"
	}
	items, err := client.KeywordSearch(l.ctx, libthreads.KeywordSearchOptions{
		Query: keyword, Limit: limit, SearchType: searchType,
	})
	if err != nil {
		return nil, app.For(code.ThreadsAccount).SvcThirdParty("keyword_search 失敗：" + err.Error())
	}
	list := make([]types.ContentFormulaSearchPostData, 0, len(items))
	for _, item := range items {
		text := strings.TrimSpace(item.Text)
		if text == "" {
			continue
		}
		author := strings.TrimSpace(item.Username)
		list = append(list, types.ContentFormulaSearchPostData{
			Text:            text,
			Author:          author,
			Permalink:       item.Permalink,
			MediaID:         item.ID,
			LikeCount:       item.LikeCount,
			ReplyCount:      item.ReplyCount,
			EngagementScore: libviral.ScorePost(item.LikeCount, item.ReplyCount),
		})
	}
	return &types.SearchContentFormulaPostsData{
		List:    list,
		Message: fmt.Sprintf("找到 %d 篇相似貼文", len(list)),
	}, nil
}
