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

package favorites

import (
	"context"

	"juwan-backend/app/search/api/internal/svc"
	"juwan-backend/app/search/api/internal/types"
	"juwan-backend/app/search/rpc/searchservice"
	"juwan-backend/common/utils/contextj"

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

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

// 获取收藏列表
func NewListFavoritesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListFavoritesLogic {
	return &ListFavoritesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListFavoritesLogic) ListFavorites(req *types.PageReq) (resp *types.FavoriteListResp, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	limit := req.Limit
	if limit <= 0 {
		limit = 20
	}

	out, err := l.svcCtx.SearchRpc.SearchFavorites(l.ctx, &searchservice.SearchFavoritesReq{
		Offset: req.Offset,
		Limit:  limit,
		UserId: &uid,
	})
	if err != nil {
		return nil, err
	}
	items := make([]types.Favorite, 0, len(out.GetFavorites()))
	for _, item := range out.GetFavorites() {
		items = append(items, toAPIFavorite(item))
	}

	return &types.FavoriteListResp{
		Items: items,
		Meta: types.PageMeta{
			Total:  int64(len(items)),
			Offset: req.Offset,
			Limit:  limit,
		},
	}, nil
}
