package basic

import (
	"context"
	"time"

	"bsm/full/module/finance/wallet/internal/impl"
	"bsm/full/module/finance/wallet/internal/models"
	pb "bsm/full/module/finance/wallet/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"
)

// 添加银行卡
func AddBankCard(ctx context.Context, in *pb.AddBankCardRequest) (reply *pb.StatusReply, err error) {
	auth, ok := service.ParseMetaCtx(ctx, nil)
	if ok != nil {
		return nil, ok
	}

	if in.Phone == "" || in.IdCard == "" || in.CardNo == "" || in.CardOwner == "" {
		return nil, errcode.ErrInvalidArgument
	}

	myWallet, err := models.GetWalletByPassportIdentity(auth.ID, auth.Identity)
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	// Try to enrich bank meta if exists locally; ignore not found.
	var cardInfo models.WalletBank
	_ = impl.DBService.Where("card_no = ?", in.CardNo).First(&cardInfo).Error

	data := &models.WalletBank{
		WalletIdentity: myWallet.Identity,
		CardNo:         in.CardNo,
		BankName:       cardInfo.BankName,
		Bank:           cardInfo.Bank,
		BankType:       cardInfo.BankType,
		CardOwner:      in.CardOwner,
		IDCard:         in.IdCard,
		Phone:          in.Phone,
	}

	data.Identity = utils.UUID()
	data.PassportID = auth.ID
	data.PassportIdentity = auth.Identity

	err = impl.DBService.Create(&data).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	return &pb.StatusReply{
		Message: vars.OK,
		Timeseq: time.Now().UnixMilli(),
	}, nil
}
