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"
	"juwan-backend/app/snowflake/rpc/snowflake"

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

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

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

// -----------------------commentLikes-----------------------
func (l *AddCommentLikesLogic) AddCommentLikes(in *pb.AddCommentLikesReq) (*pb.AddCommentLikesResp, error) {
	if in.GetCommentId() <= 0 || in.GetUserId() <= 0 {
		return nil, errors.New("commentId and userId are required")
	}

	exists, err := l.svcCtx.CommunityModelRO.Comments.Query().
		Where(comments.IDEQ(in.GetCommentId()), comments.DeletedAtIsNil()).
		Exist(l.ctx)
	if err != nil || !exists {
		return nil, errors.New("comment not found")
	}

	dup, _ := l.svcCtx.CommunityModelRO.CommentLikes.Query().
		Where(commentlikes.CommentIDEQ(in.GetCommentId()), commentlikes.UserIDEQ(in.GetUserId())).
		Exist(l.ctx)
	if dup {
		return &pb.AddCommentLikesResp{}, nil
	}

	idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
	if err != nil {
		return nil, errors.New("create comment like id failed")
	}

	_, err = l.svcCtx.CommunityModelRW.CommentLikes.Create().
		SetID(idResp.Id).
		SetCommentID(in.GetCommentId()).
		SetUserID(in.GetUserId()).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("addCommentLikes err: %v", err)
		return nil, errors.New("add comment like failed")
	}

	l.svcCtx.CommunityModelRW.Comments.Update().
		Where(comments.IDEQ(in.GetCommentId())).
		AddLikeCount(1).
		Exec(l.ctx)

	return &pb.AddCommentLikesResp{}, nil
}
