// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2

package community

import (
	"context"
	"strconv"

	"juwan-backend/app/community/api/internal/svc"
	"juwan-backend/app/community/api/internal/types"
	communitypb "juwan-backend/app/community/rpc/pb"
	"juwan-backend/common/utils/contextj"

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

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

// 发布帖子
func NewCreatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePostLogic {
	return &CreatePostLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreatePostLogic) CreatePost(req *types.CreatePostReq) (resp *types.Post, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	linkedOrderID := int64(0)
	if req.LinkedOrderId != "" {
		linkedOrderID, _ = strconv.ParseInt(req.LinkedOrderId, 10, 64)
	}
	_, err = l.svcCtx.CommunityRpc.AddPosts(l.ctx, &communitypb.AddPostsReq{
		AuthorId:      uid,
		AuthorRole:    "consumer",
		Title:         req.Title,
		Content:       req.Content,
		Images:        req.Images,
		Tags:          req.Tags,
		LinkedOrderId: linkedOrderID,
	})
	if err != nil {
		return nil, err
	}
	posts, err := l.svcCtx.CommunityRpc.SearchPosts(l.ctx, &communitypb.SearchPostsReq{
		Offset:   0,
		Limit:    1,
		AuthorId: &uid,
	})
	if err != nil || len(posts.GetPosts()) == 0 {
		return nil, err
	}
	out := mapPost(l.ctx, l.svcCtx, posts.GetPosts()[0], false)
	return &out, nil

}
