package persona

import (
	"context"
	"strings"

	scanpostusecase "haixun-backend/internal/model/scan_post/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *ListPersonaViralScanPostsLogic) ListPersonaViralScanPosts(
	req *types.ListPersonaViralScanPostsHandlerReq,
) (*types.ListPersonaViralScanPostsData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.ID)
	if _, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, personaID); err != nil {
		return nil, err
	}

	limit := 100
	if req.Limit > 0 {
		limit = req.Limit
	}
	posts, err := l.svcCtx.ScanPost.ListForPersona(l.ctx, scanpostusecase.PersonaListRequest{
		TenantID:  tenantID,
		OwnerUID:  uid,
		PersonaID: personaID,
		Limit:     limit,
	})
	if err != nil {
		return nil, err
	}

	list := make([]types.ViralScanPostData, 0, len(posts))
	for _, post := range posts {
		list = append(list, types.ViralScanPostData{
			ID:              post.ID,
			SearchTag:       post.SearchTag,
			Permalink:       post.Permalink,
			Author:          post.Author,
			AuthorVerified:  post.AuthorVerified,
			FollowerCount:   post.FollowerCount,
			Text:            post.Text,
			LikeCount:       post.LikeCount,
			ReplyCount:      post.ReplyCount,
			EngagementScore: post.EngagementScore,
			Source:          post.Source,
			ScanJobID:       post.ScanJobID,
			Replies:         viralScanReplies(post.Replies),
			CreateAt:        post.CreateAt,
		})
	}
	return &types.ListPersonaViralScanPostsData{List: list, Total: len(list)}, nil
}

func viralScanReplies(replies []scanpostusecase.ScanReplySummary) []types.ScanReplyData {
	if len(replies) == 0 {
		return nil
	}
	out := make([]types.ScanReplyData, 0, len(replies))
	for _, reply := range replies {
		out = append(out, types.ScanReplyData{
			ExternalID: reply.ExternalID,
			Author:     reply.Author,
			Text:       reply.Text,
			Permalink:  reply.Permalink,
			LikeCount:  reply.LikeCount,
			PostedAt:   reply.PostedAt,
		})
	}
	return out
}
