package friend

import (
	"context"
	"time"

	"bsm/full/module/social/relation/internal/impl"
	"bsm/full/module/social/relation/internal/logic/common"
	"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"
)

// 好友申请Do:确认
func ApplyDoPass(ctx context.Context, in *pb.ApplyDoPassRequest) (reply *pb.DataStatusReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	if in.FriendRelationIdentity == "" || in.ApplyIdentity == "" || in.FriendRelationId == 0 {
		return nil, errcode.ErrInvalidArgument
	}

	//写入好友表
	friend := &models.RelationFriend{FriendrelationID: uint(in.FriendRelationId), FriendrelationIdentity: in.FriendRelationIdentity}
	friend.Identity = utils.UUID()
	friend.PassportID = auth.ID
	friend.PassportIdentity = auth.Identity
	friend.SessionID = common.UniqueSessionID(auth.Identity, in.FriendRelationIdentity)

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

	//EventMQ：向mesh MQ中心发送报文，请求推送消息以及更新Cache.

	err = impl.DBService.Model(models.FriendApply{}).Where("to_identity=? and identity=?", auth.Identity, in.ApplyIdentity).UpdateColumn("status", 1).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	return &pb.DataStatusReply{
		Data:    vars.OK,
		Timeseq: time.Now().UnixMilli(),
	}, nil

}
