// 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"
	"juwan-backend/common/utils/contextj"

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

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

// 发表评论
func NewCreateCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCommentLogic {
	return &CreateCommentLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateCommentLogic) CreateComment(req *types.CreateCommentReq) (resp *types.Comment, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	_, err = l.svcCtx.CommunityRpc.AddComments(l.ctx, &communitypb.AddCommentsReq{
		PostId:   req.PostId,
		AuthorId: uid,
		Content:  req.Content,
	})
	if err != nil {
		return nil, err
	}
	comments, err := l.svcCtx.CommunityRpc.SearchComments(l.ctx, &communitypb.SearchCommentsReq{
		Offset:   0,
		Limit:    1,
		PostId:   req.PostId,
		AuthorId: uid,
	})
	if err != nil || len(comments.GetComments()) == 0 {
		return nil, err
	}
	out := mapComment(l.ctx, l.svcCtx, comments.GetComments()[len(comments.GetComments())-1], false)
	return &out, nil

}
