// Package basic 钱包基础业务逻辑
package basic

import (
	"context"

	"bsm/full/module/finance/wallet/internal/config"
	"bsm/full/module/finance/wallet/internal/excode"
	"bsm/full/module/finance/wallet/internal/impl"
	"bsm/full/module/finance/wallet/internal/models"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/utils"
)

// WalletPay 钱包支付结构体
type WalletPay struct {
	ctx  context.Context
	Body *models.WalletBasic
}

// NewWallet 创建钱包支付实例
// 验证用户身份、钱包状态、支付密码和余额
func NewWallet(passportIdentity, pwd string, amount int64) (*WalletPay, error) {
	// 检查钱包是否存在
	wallet := models.WalletExists(passportIdentity)
	if wallet == nil {
		return nil, errcode.ErrNotFound(404, "wallet")
	}

	// 检查钱包状态
	if wallet.Status == -1 {
		return nil, errcode.ErrPermissionDenied
	}

	// 验证支付密码
	encPassword := EncodePassword(pwd, passportIdentity)
	if encPassword != wallet.PayPassword {
		return nil, errcode.ErrPassword
	}

	// 检查余额是否足够
	if amount > wallet.Balance {
		return nil, excode.ErrBalanceNotEnough
	}

	return &WalletPay{
		Body: wallet,
	}, nil
}

// TradeConsum 执行交易消费
// 扣除钱包余额和可提现余额
func (srv *WalletPay) TradeConsum(amount int64) error {
	data := map[string]interface{}{
		"balance":            srv.Body.Balance - amount,
		"withdrawal_balance": srv.Body.WithdrawalBalance - amount,
	}
	err := impl.DBService.Model(&models.WalletBasic{}).Where("identity=?", srv.Body.Identity).UpdateColumns(data).Error
	if err != nil {
		return err
	}
	return nil
}

// EncodePassword 加密支付密码
// 使用SHA256算法对密码进行加密
func EncodePassword(pwd, passportIdentity string) string {
	return utils.Sha256(pwd, passportIdentity+config.Spec.Wallet.PublicKey)
}
