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

package community

import (
	"context"

	"juwan-backend/app/community/api/internal/svc"
	"juwan-backend/app/community/api/internal/types"
	communitypb "juwan-backend/app/community/rpc/pb"

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

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

// 获取用户帖子
func NewListUserPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListUserPostsLogic {
	return &ListUserPostsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListUserPostsLogic) ListUserPosts(req *types.ListCommentsReq) (resp *types.PostListResp, err error) {
	if req.Limit <= 0 {
		req.Limit = 20
	}
	authorID := req.Id
	out, err := l.svcCtx.CommunityRpc.SearchPosts(l.ctx, &communitypb.SearchPostsReq{Offset: req.Offset, Limit: req.Limit, AuthorId: &authorID})
	if err != nil {
		return nil, err
	}
	uid := currentUserIDOrZero(l.ctx)
	items := make([]types.Post, 0, len(out.GetPosts()))
	for _, p := range out.GetPosts() {
		liked := false
		if uid > 0 {
			likes, e := l.svcCtx.CommunityRpc.SearchPostLikes(l.ctx, &communitypb.SearchPostLikesReq{Offset: 0, Limit: 1, PostId: &p.Id, UserId: &uid})
			liked = e == nil && len(likes.GetPostLikes()) > 0
		}
		items = append(items, mapPost(l.ctx, l.svcCtx, p, liked))
	}
	return &types.PostListResp{Items: items, Meta: types.PageMeta{Total: int64(len(items)), Offset: req.Offset, Limit: req.Limit}}, nil

}
