package friend

import (
	"context"
	"time"

	"bsm/full/module/social/relation/internal/impl"
	"bsm/full/module/social/relation/internal/models"
	pb "bsm/full/module/social/relation/pb"
	"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/utils"
	"git.apinb.com/bsm-sdk/core/vars"
)

// 好友申请
func ApplyDo(ctx context.Context, in *pb.ApplyDoRequest) (reply *pb.DataStatusReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	if in.ToIdentity == "" || in.Body == "" || in.ToId == 0 {
		return nil, errcode.ErrInvalidArgument
	}

	//创建申请
	apply := models.FriendApply{
		FromID:        uint(auth.ID),
		FromIdentity:  auth.Identity,
		ToID:          uint(in.ToId),
		ToIdentity:    in.ToIdentity,
		LastMessageID: 0,
	}
	apply.Identity = utils.UUID()
	err = impl.DBService.Create(&apply).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	//创建留言
	msg := models.FriendApplyMessage{
		ApplyID: apply.ID,
		Body:    in.Body,
	}
	msg.PassportID = auth.ID
	msg.PassportIdentity = auth.Identity

	err = impl.DBService.Create(&msg).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	//回写最后一次交流的消息ID
	err = impl.DBService.Model(models.FriendApply{}).Where("id=?", apply.ID).UpdateColumn("last_message_id", msg.ID).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	//EventMQ：向mesh MQ中心发送报文，请求推送消息以及更新Cache.
	return &pb.DataStatusReply{
		Data:    vars.OK,
		Timeseq: time.Now().UnixMilli(),
	}, nil

}
