package logic

import (
	"context"
	"errors"

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

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

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

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

func (l *UpdateCommentLikesLogic) UpdateCommentLikes(in *pb.UpdateCommentLikesReq) (*pb.UpdateCommentLikesResp, error) {
	if in.GetCommentId() <= 0 || in.GetUserId() <= 0 {
		return nil, errors.New("commentId and userId are required")
	}

	_, err := l.svcCtx.CommunityModelRO.CommentLikes.Query().
		Where(commentlikes.CommentIDEQ(in.GetCommentId()), commentlikes.UserIDEQ(in.GetUserId())).
		First(l.ctx)
	if err != nil {
		return nil, errors.New("comment like not found")
	}

	_, err = l.svcCtx.CommunityModelRW.CommentLikes.Update().
		Where(commentlikes.CommentIDEQ(in.GetCommentId()), commentlikes.UserIDEQ(in.GetUserId())).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("updateCommentLikes err: %v", err)
		return nil, errors.New("update comment like failed")
	}

	return &pb.UpdateCommentLikesResp{}, nil
}
