package logic

import (
	"context"

	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"

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

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

func NewCommentPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentPostLogic {
	return &CommentPostLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 评论帖子
func (l *CommentPostLogic) CommentPost(in *plant.CommentPostReq) (*plant.CommonResp, error) {
	err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		comment := plantModel.PostComment{
			PostID:   in.PostId,
			UserID:   in.UserId,
			Content:  in.Content,
			ParentID: in.ParentId,
		}
		if err := tx.Create(&comment).Error; err != nil {
			return err
		}
		return tx.Model(&plantModel.Post{}).Where("id = ?", in.PostId).
			Update("comment_count", gorm.Expr("comment_count + 1")).Error
	})
	if err != nil {
		return nil, err
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
