package post

import (
	"context"
	"time"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/types"
	"git.apinb.com/bsm-sdk/core/utils"
	"bsm/full/module/social/feed/internal/models"
	pb "bsm/full/module/social/feed/pb"
)

// 新建推文
func Create(ctx context.Context, in *pb.PostItem) (reply *pb.StatusReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	if in.GetContent() == "" {
		return nil, errcode.ErrInvalidArgument
	}
	var postData = models.FeedPost{
		Std_IICUDS:   types.Std_IICUDS{Identity: utils.UUID()},
		Std_Passport: types.Std_Passport{PassportID: auth.ID, PassportIdentity: auth.Identity},
		Content:      in.Content,
		IsOpen:       in.IsOpen,
	}

	if len(in.GetAttachs()) > 0 {
		for _, val := range in.Attachs {
			postData.Attachs = append(postData.Attachs, models.FeedRelateAttach{
				PostIdentity: postData.Std_IICUDS.Identity,
				Identity:     utils.UUID(),
				AttachType:   val.AttachType,
				Url:          val.Url,
			})
		}
	}
	if len(in.GetTags()) > 0 {
		for _, val := range in.Tags {
			postData.Tags = append(postData.Tags, models.FeedRelateTags{
				PostIdentity: postData.Std_IICUDS.Identity,
				Content:      val.Content,
				Key:          val.Key,
			})
		}
	}
	err = models.CreatePost(&postData)
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.StatusReply{
		Data:    postData.Identity,
		Timeseq: time.Now().UnixNano(),
	}, nil

}
