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

// 获取帖子评论
func NewListCommentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListCommentsLogic {
	return &ListCommentsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListCommentsLogic) ListComments(req *types.ListCommentsReq) (resp *types.CommentListResp, err error) {
	if req.Limit <= 0 {
		req.Limit = 20
	}
	out, err := l.svcCtx.CommunityRpc.SearchComments(l.ctx, &communitypb.SearchCommentsReq{
		Offset: req.Offset,
		Limit:  req.Limit,
		PostId: req.Id,
	})
	if err != nil {
		return nil, err
	}
	uid := currentUserIDOrZero(l.ctx)
	items := make([]types.Comment, 0, len(out.GetComments()))
	for _, c := range out.GetComments() {
		liked := false
		if uid > 0 {
			likes, e := l.svcCtx.CommunityRpc.SearchCommentLikes(l.ctx, &communitypb.SearchCommentLikesReq{Offset: 0, Limit: 1, CommentId: c.Id, UserId: uid})
			liked = e == nil && len(likes.GetCommentLikes()) > 0
		}
		items = append(items, mapComment(l.ctx, l.svcCtx, c, liked))
	}
	return &types.CommentListResp{Items: items, Meta: types.PageMeta{Total: int64(len(items)), Offset: req.Offset, Limit: req.Limit}}, nil

}
