// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package brand

import (
	"context"
	"strings"

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

	"github.com/zeromicro/go-zero/core/logx"
)

type ListBrandScanPostsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListBrandScanPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListBrandScanPostsLogic {
	return &ListBrandScanPostsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListBrandScanPostsLogic) ListBrandScanPosts(req *types.ListBrandScanPostsHandlerReq) (resp *types.ListBrandScanPostsData, err error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	if _, err := l.svcCtx.Brand.Get(l.ctx, tenantID, uid, req.ID); err != nil {
		return nil, err
	}

	listReq := scanpostusecase.ListRequest{
		TenantID: tenantID,
		OwnerUID: uid,
		BrandID:  req.ID,
		Limit:    100,
	}
	listReq.Priority = strings.TrimSpace(req.Priority)
	listReq.Recent7dOnly = req.Recent7d
	listReq.ProductFitMin = req.ProductFitMin
	if req.Limit > 0 {
		listReq.Limit = req.Limit
	}

	posts, err := l.svcCtx.ScanPost.List(l.ctx, listReq)
	if err != nil {
		return nil, err
	}

	list := make([]types.ScanPostData, 0, len(posts))
	for _, post := range posts {
		list = append(list, types.ScanPostData{
			ID:                 post.ID,
			GraphNodeID:        post.GraphNodeID,
			SearchTag:          post.SearchTag,
			QueryDimension:     post.QueryDimension,
			ExternalID:         post.ExternalID,
			Permalink:          post.Permalink,
			Author:             post.Author,
			Text:               post.Text,
			Priority:           post.Priority,
			PlacementScore:     post.PlacementScore,
			ProductFitScore:    post.ProductFitScore,
			SolvedByProduct:    post.SolvedByProduct,
			Source:             post.Source,
			ScanJobID:          post.ScanJobID,
			OutreachStatus:     post.OutreachStatus,
			PublishedReplyID:   post.PublishedReplyID,
			PublishedPermalink: post.PublishedPermalink,
			OutreachUpdateAt:   post.OutreachUpdateAt,
			Replies:            toScanReplyData(post.Replies),
			CreateAt:           post.CreateAt,
		})
	}
	return &types.ListBrandScanPostsData{List: list, Total: len(list)}, nil
}
