//
//  WalletCore.swift

//
//  Created by Leon on 2025/9/15.
//

class WalletCore {
    static let shared = WalletCore()

    @Published private(set) var balance: WalletInfo = WalletInfo()

    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(login), name: AppNotificationName.userLoginSuccess.notificationName, object: nil)
    }

    // MARK: - Public

    func refreshWallet(postNoti: Bool = true, block: (() -> Void)? = nil) {
        guard UserCore.shared.isLogin() else { return }

        WalletProvider.request(.myWallet, modelType: WalletInfo.self) { [weak self] result in
            switch result {
            case let .success(model):
                if let balance = model {
                    self?.balance = balance
                }
                if postNoti {
                    NotificationCenter.post(name: .walletInfoUpdated, object: nil, userInfo: nil)
                }
            case .failure:
                break
            }
            block?()
        }
    }

    // MARK: Public helper

    func displayBalance() -> String {
        return balance.displayBalance()
    }

    // MARK: - Noti

    @objc private func login() {
        refreshWallet(postNoti: true, block: nil)
    }
}
