package logic

import (
	"context"
	"errors"

	"juwan-backend/app/community/rpc/internal/models/commentlikes"
	"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 DelCommentLikesLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *DelCommentLikesLogic) DelCommentLikes(in *pb.DelCommentLikesReq) (*pb.DelCommentLikesResp, error) {
	if in.GetId() <= 0 {
		return nil, errors.New("id is required")
	}

	if in.UserId != nil && in.GetUserId() > 0 {
		n, err := l.svcCtx.CommunityModelRW.CommentLikes.Delete().
			Where(commentlikes.CommentIDEQ(in.GetId()), commentlikes.UserIDEQ(in.GetUserId())).
			Exec(l.ctx)
		if err != nil {
			logx.Errorf("delCommentLikes err: %v", err)
		}
		if n > 0 {
			l.svcCtx.CommunityModelRW.Comments.Update().
				Where(comments.IDEQ(in.GetId()), comments.LikeCountGT(0)).
				AddLikeCount(-1).
				Exec(l.ctx)
		}
		return &pb.DelCommentLikesResp{}, nil
	}

	n, err := l.svcCtx.CommunityModelRW.CommentLikes.Delete().
		Where(commentlikes.CommentIDEQ(in.GetId())).
		Exec(l.ctx)
	if err != nil {
		logx.Errorf("delCommentLikes err: %v", err)
	}
	if n > 0 {
		l.svcCtx.CommunityModelRW.Comments.Update().
			Where(comments.IDEQ(in.GetId()), comments.LikeCountGTE(n)).
			AddLikeCount(-n).
			Exec(l.ctx)
	}

	return &pb.DelCommentLikesResp{}, nil
}
