package logic

import (
	"context"
	"errors"

	"juwan-backend/app/community/rpc/internal/models/comments"
	"juwan-backend/app/community/rpc/internal/svc"
	"juwan-backend/app/community/rpc/pb"

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

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

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

func (l *UpdateCommentsLogic) UpdateComments(in *pb.UpdateCommentsReq) (*pb.UpdateCommentsResp, error) {
	if in.GetId() <= 0 {
		return nil, errors.New("id is required")
	}

	updater := l.svcCtx.CommunityModelRW.Comments.Update().
		Where(comments.IDEQ(in.GetId()), comments.DeletedAtIsNil())

	if in.GetContent() != "" {
		updater = updater.SetContent(in.GetContent())
	}
	if in.GetLikeCount() > 0 {
		updater = updater.SetLikeCount(int(in.GetLikeCount()))
	}

	n, err := updater.Save(l.ctx)
	if err != nil {
		logx.Errorf("updateComments err: %v", err)
		return nil, errors.New("update comment failed")
	}
	if n == 0 {
		return nil, errors.New("comment not found")
	}

	return &pb.UpdateCommentsResp{}, nil
}
