package placement_topic

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 ListPlacementTopicScanPostsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *ListPlacementTopicScanPostsLogic) ListPlacementTopicScanPosts(req *types.ListPlacementTopicScanPostsHandlerReq) (*types.ListBrandScanPostsData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	scope, err := resolveScope(l.ctx, l.svcCtx, tenantID, uid, req.ID)
	if err != nil {
		return nil, err
	}
	listReq := scanpostusecase.ListRequest{
		TenantID: tenantID,
		OwnerUID: uid,
		BrandID:  scope.BrandID,
		TopicID:  scope.TopicID,
		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 {
		if mapped := toScanPostData(&post); mapped != nil {
			if draft, draftErr := l.svcCtx.OutreachDraft.GetLatestByScanPost(l.ctx, tenantID, uid, scope.BrandID, scope.TopicID, post.ID); draftErr != nil {
				return nil, draftErr
			} else if draft != nil {
				mapped.LatestDraft = toOutreachDraftData(draft)
			}
			list = append(list, *mapped)
		}
	}
	return &types.ListBrandScanPostsData{List: list, Total: len(list)}, nil
}
