package login

import (
	"context"

	"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"
)

// 通过验证码登录
func Code(ctx context.Context, in *pb.LoginByCodeRequest) (reply *pb.LoginReply, err error) {
	if in.Phone == "" || in.Code == "" || in.Country == "" {
		return nil, errcode.ErrInvalidArgument
	}

	pa, err := models.GetPassportAccountByField("phone", in.Phone)
	if err != nil {
		return nil, err
	}

	data, err := models.CheckPassportData(pa.ID, pa.Identity)
	if err != nil {
		printer.Error("Get passport data by passport_id %v error:%v", pa.ID, err)
		return nil, errcode.ErrDB
	}

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

	//save token to cache.
	err = impl.RedisService.Client.Set(impl.RedisService.Ctx, vars.TokenPrefix+pa.Identity, token, 0).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.LoginReply{
		Id:       int64(pa.ID),
		Identity: pa.Identity,
		Token:    token,
		Extend:   paExtend,
		VerifyStatus: &pb.VerifyStatus{
			EmailVerify:    data.EmailVerify,
			PhoneVerify:    data.PhoneVerify,
			FaceVerify:     data.FaceVerify,
			DocumentVerify: data.DocumentVerify,
			KycVerify:      data.KycVerify,
		},
	}, nil
}
