package logic

import (
	"context"
	"errors"

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

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

// -----------------------posts-----------------------
func (l *AddPostsLogic) AddPosts(in *pb.AddPostsReq) (*pb.AddPostsResp, error) {
	if in.GetAuthorId() <= 0 {
		return nil, errors.New("authorId is required")
	}
	if in.GetTitle() == "" {
		return nil, errors.New("title is required")
	}
	if in.GetContent() == "" {
		return nil, errors.New("content is required")
	}

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

	authorRole := in.GetAuthorRole()
	if authorRole == "" {
		authorRole = "consumer"
	}

	creator := l.svcCtx.CommunityModelRW.Posts.Create().
		SetID(idResp.Id).
		SetAuthorID(in.GetAuthorId()).
		SetAuthorRole(authorRole).
		SetTitle(in.GetTitle()).
		SetContent(in.GetContent()).
		SetImages(toTextArray(in.GetImages())).
		SetTags(toTextArray(in.GetTags())).
		SetPinned(in.GetPinned())

	if in.GetLinkedOrderId() != 0 {
		creator = creator.SetLinkedOrderID(in.GetLinkedOrderId())
	}
	if in.GetQuotedPostId() != 0 {
		creator = creator.SetQuotedPostID(in.GetQuotedPostId())
	}

	_, err = creator.Save(l.ctx)
	if err != nil {
		logx.Errorf("addPosts err: %v", err)
		return nil, errors.New("add post failed")
	}

	return &pb.AddPostsResp{}, nil
}
