<?php

namespace App\Services\Wallet;

use App\Models\PlayerWallet;
use App\Services\PlayerRealtimeBroadcaster;

/**
 * 钱包余额变动后推送 `balance.update`（频道 `player.{id}`）。
 */
final class WalletBalanceRealtimeNotifier
{
    public function __construct(
        private readonly PlayerRealtimeBroadcaster $playerRealtime,
    ) {}

    public function notifyAfterMovement(
        PlayerWallet $wallet,
        int $changeMinor,
        string $bizType,
    ): void {
        if ($changeMinor === 0) {
            return;
        }

        $reason = $this->mapBizTypeToReason($bizType);
        if ($reason === null) {
            return;
        }

        $this->playerRealtime->notifyBalanceUpdate(
            (int) $wallet->player_id,
            (string) $wallet->currency_code,
            (int) $wallet->balance,
            $changeMinor,
            $reason,
        );
    }

    private function mapBizTypeToReason(string $bizType): ?string
    {
        return match ($bizType) {
            'transfer_in' => 'transfer_in',
            'transfer_out' => 'transfer_out',
            'transfer_out_refund', 'bet_reverse', 'reversal' => 'refund',
            'bet_deduct' => 'bet',
            'settle_payout', 'jackpot_manual_payout' => 'prize',
            default => null,
        };
    }
}
