package login

import (
	"context"
	"errors"

	"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"
	"gorm.io/gorm"
)

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

	var pa models.PassportAccount
	err = impl.DBService.Where("phone = ?", in.Phone).First(&pa).Error
	if err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			printer.Error("Get passport account by phone %v error:%v", in.Phone, err)
			return nil, errcode.ErrDB
		}
		pa = models.PassportAccount{
			Std_IICUDS: types.Std_IICUDS{
				Identity: utils.UUID(),
				Status:   vars.Status_Normal,
			},
			Account: in.Phone,
			Phone:   in.Phone,
		}

		err = impl.DBService.Create(&pa).Error
		if 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,
		}

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

	if pa.Status == vars.Status_Disable {
		return nil, errcode.ErrPermissionDenied
	}

	var data models.PassportData
	err = impl.DBService.Where("passport_id = ?", pa.ID).First(&data).Error
	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
	}

	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
}
