package logic

import (
	"context"
	"errors"

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

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

// -----------------------postLikes-----------------------
func (l *AddPostLikesLogic) AddPostLikes(in *pb.AddPostLikesReq) (*pb.AddPostLikesResp, error) {
	if in.GetPostId() <= 0 || in.GetUserId() <= 0 {
		return nil, errors.New("postId and userId are required")
	}

	exists, err := l.svcCtx.CommunityModelRO.Posts.Query().
		Where(posts.IDEQ(in.GetPostId()), posts.DeletedAtIsNil()).
		Exist(l.ctx)
	if err != nil || !exists {
		return nil, errors.New("post not found")
	}

	dup, _ := l.svcCtx.CommunityModelRO.PostLikes.Query().
		Where(postlikes.PostIDEQ(in.GetPostId()), postlikes.UserIDEQ(in.GetUserId())).
		Exist(l.ctx)
	if dup {
		return &pb.AddPostLikesResp{}, nil
	}

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

	_, err = l.svcCtx.CommunityModelRW.PostLikes.Create().
		SetID(idResp.Id).
		SetPostID(in.GetPostId()).
		SetUserID(in.GetUserId()).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("addPostLikes err: %v", err)
		return nil, errors.New("add post like failed")
	}

	l.svcCtx.CommunityModelRW.Posts.Update().
		Where(posts.IDEQ(in.GetPostId())).
		AddLikeCount(1).
		Exec(l.ctx)

	return &pb.AddPostLikesResp{}, nil
}
