package logic

import (
	"context"
	"errors"

	"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 UpdatePostsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *UpdatePostsLogic) UpdatePosts(in *pb.UpdatePostsReq) (*pb.UpdatePostsResp, error) {
	if in.GetId() <= 0 {
		return nil, errors.New("id is required")
	}

	updater := l.svcCtx.CommunityModelRW.Posts.Update().
		Where(posts.IDEQ(in.GetId()), posts.DeletedAtIsNil())

	if in.AuthorId != nil {
		updater = updater.SetAuthorID(in.GetAuthorId())
	}
	if in.AuthorRole != nil {
		updater = updater.SetAuthorRole(in.GetAuthorRole())
	}
	if in.Title != nil {
		updater = updater.SetTitle(in.GetTitle())
	}
	if in.Content != nil {
		updater = updater.SetContent(in.GetContent())
	}
	if len(in.Images) > 0 {
		updater = updater.SetImages(toTextArray(in.GetImages()))
	}
	if len(in.Tags) > 0 {
		updater = updater.SetTags(toTextArray(in.GetTags()))
	}
	if in.LinkedOrderId != nil {
		updater = updater.SetLinkedOrderID(in.GetLinkedOrderId())
	}
	if in.QuotedPostId != nil {
		updater = updater.SetQuotedPostID(in.GetQuotedPostId())
	}
	if in.LikeCount != nil {
		updater = updater.SetLikeCount(int(in.GetLikeCount()))
	}
	if in.CommentCount != nil {
		updater = updater.SetCommentCount(int(in.GetCommentCount()))
	}
	if in.Pinned != nil {
		updater = updater.SetPinned(in.GetPinned())
	}

	n, err := updater.Save(l.ctx)
	if err != nil {
		logx.Errorf("updatePosts err: %v", err)
		return nil, errors.New("update post failed")
	}
	if n == 0 {
		return nil, errors.New("post not found")
	}

	return &pb.UpdatePostsResp{}, nil
}
