package logic

import (
	"context"
	"errors"
	"time"

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

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

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

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

func (l *DelCommentsLogic) DelComments(in *pb.DelCommentsReq) (*pb.DelCommentsResp, error) {
	if in.GetId() <= 0 {
		return nil, errors.New("id is required")
	}

	comment, err := l.svcCtx.CommunityModelRO.Comments.Query().
		Where(comments.IDEQ(in.GetId()), comments.DeletedAtIsNil()).
		First(l.ctx)
	if err != nil {
		return &pb.DelCommentsResp{}, nil
	}

	now := time.Now()
	_, err = l.svcCtx.CommunityModelRW.Comments.Update().
		Where(comments.IDEQ(in.GetId()), comments.DeletedAtIsNil()).
		SetDeletedAt(now).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("delComments err: %v", err)
	}

	l.svcCtx.CommunityModelRW.Posts.Update().
		Where(posts.IDEQ(comment.PostID), posts.DeletedAtIsNil(), posts.CommentCountGT(0)).
		AddCommentCount(-1).
		Exec(l.ctx)

	return &pb.DelCommentsResp{}, nil
}
