/**
 * @Author: ZhaoYadong
 * @Date: 2024-02-27 21:09:45
 * @LastEditors: ZhaoYadong
 * @LastEditTime: 2024-02-28 11:50:05
 * @FilePath: /server/Users/edy/go/src/passport/internal/logic/register/do.go
 */
package register

import (
	"bsm/full/module/base/passport/internal/config"
	"bsm/full/module/base/passport/internal/impl"
	"bsm/full/module/base/passport/internal/logic/common"
	"bsm/full/module/base/passport/internal/models"
	"bsm/full/module/base/passport/internal/vars"
	pb "bsm/full/module/base/passport/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/types"
	"git.apinb.com/bsm-sdk/core/utils"
	_vars "git.apinb.com/bsm-sdk/core/vars"
	"golang.org/x/crypto/bcrypt"
)

// Do .
func Do(in *pb.RegisterRequest) (*pb.RegisterReply, error) {
	var salt string
	if in.Password != "" {
		salt = utils.UUID()
		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(in.Password+salt), bcrypt.MinCost)
		if err != nil {
			return nil, errcode.ErrInternal
		}
		in.Password = string(hashedPassword)
	}

	var account = in.Account
	if account == "" {
		account = in.Phone
	}
	pa := models.PassportAccount{
		Std_IICUDS: types.Std_IICUDS{
			Identity: utils.UUID(),
			Status:   vars.Status_Normal,
		},
		Account:  account,
		Phone:    in.Phone,
		Password: in.Password,
		Salt:     salt,
	}

	// 插入passport 基础表
	if err := impl.DBService.Create(&pa).Error; err != nil {
		printer.Error("create passport account and password extend by data  %+v error:%v", pa, err)
		return nil, errcode.ErrDB
	}

	data := models.PassportData{
		Std_Passport: types.Std_Passport{
			PassportID:       pa.ID,
			PassportIdentity: pa.Identity,
		},
		Country:       in.Country,
		AgencyId:      uint(in.AgencyId),
		StaffId:       uint(in.StaffId),
		OwnerId:       uint(in.OwnerId),
		OwnerIdentity: in.OwnerIdentity,
	}

	if err := impl.DBService.Create(&data).Error; err != nil {
		printer.Error("create passport data by data  %+v error:%v", data, err)
		return nil, errcode.ErrDB
	}

	extend := map[string]string{
		"rights": data.Rights,
	}
	token, err := common.GenerateTokenAes(uint(pa.ID), pa.Identity, "", data.Rights, extend)
	if err != nil {
		return nil, err
	}

	//save token to cache.
	err = impl.RedisService.Client.Set(impl.RedisService.Ctx, config.Spec.Token.Prefix+pa.Identity, token, _vars.JwtExpire).Err()
	if err != nil {
		printer.Error("Set redis cache by key %v error:%v", vars.TokenPrefix+pa.Identity, err)
		return nil, errcode.ErrInternal
	}

	return &pb.RegisterReply{
		Id:       int64(pa.ID),
		Identity: pa.Identity,
		Token:    token,
		Extend:   extend,
		VerifyStatus: &pb.VerifyStatus{
			EmailVerify:    0,
			PhoneVerify:    0,
			FaceVerify:     0,
			DocumentVerify: 0,
			KycVerify:      0,
		},
	}, nil
}
