// 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 {
		if mapped := toScanPostData(&post); mapped != nil {
			if draft, draftErr := l.svcCtx.OutreachDraft.GetLatestByScanPost(l.ctx, tenantID, uid, req.ID, "", 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
}
