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"
	_vars "git.apinb.com/bsm-sdk/core/vars"
	"golang.org/x/crypto/bcrypt"
)

// 通过密码登录
func Pwd(ctx context.Context, in *pb.LoginByPwdRequest) (reply *pb.LoginReply, err error) {
	if in.Account == "" || in.Password == "" {
		return nil, errcode.ErrInvalidArgument
	}
	pa, err := models.GetPassportAccountByField("account", in.Account)
	if err != nil {
		return nil, err
	}

	err = bcrypt.CompareHashAndPassword([]byte(pa.Password), []byte(in.Password+pa.Salt))
	if err != nil {
		return nil, errcode.NewError(187, "Passport Error")
	}

	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, _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.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
}
